Marshaling a pointer to char array into Unmanaged C++

I am calling a C++ api and it returns me a structure of function pointers. One of the functions takes in a pointer to an array of char pointers.

The problem I am having is how to declare my delegate inside the managed stuct, so that when I call this function the array gets marshaled correctly into the unmanaged code.


C++:

typedef const char *lString;

int (*Foo)(lString **resultArrayPtr); // Function pointer in C++


C#

[StructLayout(LayoutKind.Sequential)]
public struct LimeTradingSystemStruct
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate Int32 Foo([In,Out]String[] resultArrayPtr);
.
...

public Foo FooFunc;
.
...
}



Answer this question

Marshaling a pointer to char array into Unmanaged C++

  • Jyothi G

    I apologize I should have been more clear. I call an unmanaged C++ api called "GetFunctionPointers()" which returns a me a structure containing several function pointers. One of these function pointers takes in as a parameter the following:

    Unmanaged C++

    typedef const char *lString;
    int (*foo)(lString **resultArrayPtr);


    My question is how do I declare my delegate to accept a pointer to an array of character pointers I tried the following:

    Managed C#

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate Int32 Foo([In,Out]String[] resultArrayPtr); // This does not work..


  • Claudeb1965

    See Marshal.GetFunctionPointerForDelegate and Marshal.GetDelegateForFunctionPointer Methods. I din't understand from your description whether Foo function is managed or unmanaged. Anyway, you need one of these methods.
  • Badhris

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate Int32 Foo(ref IntPtr);

    Having IntPtr filled by Foo function, read all pointers pointed by it using Marshal.Copy Method (IntPtr, Int32[], Int32, Int32) method. Result is Int32[] array. For every array member, create IntPtr pointer - it points to unmanaged string from array. Extract every string using Marshal.PtrToStringAnsi method.


  • Marshaling a pointer to char array into Unmanaged C++