Linking static libraries in Visual C++ + passing Byte[] to native C functions?

I am writing a C++ .NET wrapper around some native C functions to provide a .NET interface for these functions for my C# application.

I want to link a static library and call some of its functions that use a pointer to a native char buffer.

I want my C++ .NET code to do this:

int nBytes = 100;

Byte[] byteArray = new Byte[nBytes];

external_Cfunction(byteArray, nBytes);

// Where external_CFunction is declared as:
void external_CFunction(char* charArray, int nbytes);

I don't have the source code for external_CFunction, just the .h include file and the static library.

How do I call the C function, which expects a pointer to a native C character array, with a parameter which is a reference to a .NET Byte[]

Thanks, David.



Answer this question

Linking static libraries in Visual C++ + passing Byte[] to native C functions?

  • Andranik Khachatryan

    Thanks, this has been a great help.

    David.


  • sgujjar

    You have two options:

    1) Allocate unmanaged memory block using Marshal::AllocHGlobal function, copy byteArray to it using Marshal.Copy function, and call C function with pointer returned by Marshal::AllocHGlobal.

    2) Using GCHandle structure you can get unmanaged pointer to managed array. To do this, create GCHandle instance using GCHandle.Alloc(byteArray , GCHandleType::Pinned), and get unmanaged pointer using GCHandle.AddrOfPinnedObject method. Pass this pointer to C function.

    In both cases you get IntPtr instance which can be converted void* using IntPtr.ToPointer method, and casted to char*.


  • Linking static libraries in Visual C++ + passing Byte[] to native C functions?