Thursday, May 5, 2011

Expose Borland C++ methods to C#

I have following method in my Borland C++ code,

static bool UploadBitstream(void)
{
   //Some code Implementation
}

And I'm trying to convert it to DLL and access it in C#.

What are the steps I need to follow to Convert the code DLL and then use it in C# ??

From stackoverflow
  • Once you've compiled your DLL all you should need to do in .NET to get access to it is use the DLLImport property.

    public class stuff
    {
        [DLLImport("somedll.dll")]
        public static extern void UploadBitstream();
    }
    

    If you need pointers or anything like that it gets more complicated but for void functions it's that simple.

    It should be noted that once you invoke that function the dll will be loaded by your program and won't be released until your program is closed. You can dynamically load dlls but that is much more complicated. I can explain it here if you have a need.

  • First, you have to make sure that the methods are defined extern. Then you need to declare the method stdcall or pascal calling convention, and mark them dllexport. See code listing below (this is ancient memory for me, so pardon if I am a bit off on modern Borland C++ compilers).

    // code.h
    extern "C" {
    
    #define FUNCTION __declspec(dllexport)
    
    FUNCTION int __stdcall   SomeFunction(int Value);
    

    In the main

    #include "code.h"
    
    FUNCTION int __stdcall SomeFunction(int timesThree)
    {
        return timesThree * 3;
    }
    
    Prashant : Thanks Kris, it worked well, but I have one more thing to ask... I have borland installed on my PC. But if I test it on anther PC I always get "Unable to load DLL" exception... Any suggestions??
    Kris Erickson : Check the DLL with dependency walker, there is probably a library DLL's that is required (though, the one thing I used to love about Borland was it statically linked almost all the libraries it needed so you didn't have to worry about that as much as you did with Visual C++).
  • Watch your terminology.
    In your example UploadBitstream is function not a method.
    If it is indeed a method in a class then it is very difficult to use classes from Borland compiled DLLs.

    If your code is actually C not C++ you should be able to create a compatible DLL for your simple C style functions with C++ Builder.

    See the following SO question: Use a dll from a c++ program. (borland c++ builder and in general) where I list various compiler settings which will also apply to creating compatible DLLs.

0 comments:

Post a Comment