0

I am working on C#.Net application which uses C-based library. As it needs C# Wrapper I am implementing code to marshal functions from C-based library to be accessible in C# and map data type correctly.

I have a function in library which Takes A char array by reference, The function contains logic to update array with values in it. So, At function call we can pass null array and access result value after its been called.

Objective: to pass null char array and return value by reference

The C-dll function:

int function_call(char ** var);

The C function call code:

char *name = NULL;
int val = function_Call(&name);

The C# wrapper code:

[DllImport("mylibrary.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int function_call([In] string[] val);

The C# function call code:

 string[] name = null;
 int ret = function_call(name);

I came across similar queries :

  1. How to get char** using C#? [duplicate]
  2. How do I marshal a pointer to an array of pointers to structures?

  3. marshaling char**

  4. C# equivalent to C const char**

Tried all of them but did not work. returns null value. Is there a simple working way to marshal Char ** ?

akshay dhule
  • 167
  • 3
  • 17
  • 1
    Our main application is also in C, and I have been developing a very integral module in C#. After reviewing all the options, we decided to use a C++/CLI bridge. I've been building it up for the past couple weeks, and I must say, I really enjoy using it. It really beats the hell out of data marshalling, as you can step from C into C# and back in your debugger. This way, C# code becomes really integrated with C code. Data conversion is another great plus. You'll have no trouble dealing with any data types , including complex structures. Let me know if you'd like more info. – Nik Oct 13 '17 at 22:51
  • BTW, if your main application is in C#, the bridge will work just as well. In fact, that's a much more common use of C++/CLI. – Nik Oct 13 '17 at 22:52
  • In C# arrays are derived from System.Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself. – VTodorov Oct 13 '17 at 22:53
  • It's not an array. How is the caller expected to deallocate? – David Heffernan Oct 14 '17 at 08:33
  • @Nik : Actually, I was able to marshal simple datatypes just not double pointer. – akshay dhule Oct 15 '17 at 19:33

1 Answers1

0

You can simply marshal it as IntPtr :

[DllImport("mylibrary.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int function_call(IntPtr val);

Just that on function call side, allocate mem to pointer and to access the data held by pointer : Marshal data from an unmanaged block of memory to the type specified by a generic type parameter.

akshay dhule
  • 167
  • 3
  • 17