开发者

C++/CLI or C# P/Invoke for a big C library, calling an extern function

Now I know there are quite a few questions regarding this but in general they refer to c++ libraries.

I have a fairly important C dll (app开发者_JAVA技巧roximately 2800 functions) and I need to make an API for about 70 of these callable in C#. I started off using P/Invoke but it's pretty tedious because I have complex structures to pass and return from the C code (structures with pointers to others, double pointers, etc) and it's taking me alot of time to get what I need.

Now I don't know C++/CLI at all but I have a bit of experience with C++ (not a lot though).

I am wondering if it's worth making the effort to learn this for my project. Will using a C++ wrapper enable me not to have to struggle with marshalling structures, allocating pointers in global heap, etc or not?....

Thanks a lot and big ups to this great community


That's quite a large surface area. I think C++/CLI will be easier than P/invoke. You don't need to use any C++ features, you can write what is essentially C and compile and export it with C++/CLI.


It is hard to deal with native structs from C#. So writing a C++/CLI wrapper is easier. You can convert/wrap those structs to ref classes without too much trouble and use them in C#.

void some_function(Some_Struct * ss)
{
  //...
}

struct Some_Struct
{
  int intVal;
  double dblVal;
}

//C++/ClI
public ref class Wrapper
{
  public:
    void CallSomeFunction(int intval, double doubleval)
    {
      Some_Struct * ss = new Some_Struct(); // maybe malloc is more appropriate.
      ss->intVal = intval;
      ss->dblVal = doubleval;
      some_function(ss);
      delete ss; // or Free(ss);
    }
}

//C#
Wrapper wrapper = new Wrapper();
wrapper.CallSomeFunction(10,23.3);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜