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 (approximately 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


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);

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.

链接地址: http://www.djcxy.com/p/59852.html

上一篇: 从.NET调用Java / AXIS Web服务:“返回null”问题

下一篇: C ++ / CLI或C#P /调用一个大的C库,调用一个extern函数