C # C ++ DLL call passing pointer-to-pointer argument

Could you guys help me solve the following problem? I have a C ++ dll function and it will be called by another C # application. One of the functions I need is as follows:

struct DataStruct { unsigned char* data; int len; }; DLLAPI int API_ReadFile(const wchar_t* filename, DataStruct** outData); 

I wrote the following code in C #:

 class CS_DataStruct { public byte[] data; public int len; } [DllImport("ReadFile.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] private static extern int API_ReadFile([MarshalAs(UnmanagedType.LPWStr)]string filename, ref CS_DataStruct data); 

Unfortunately, the code above does not work ... I think this is because C ++ func takes a pointer to a DataStruct pointer, and I just passed the CS_DataStruct link to.

Can I learn how to pass a pointer to a pointer to a C ++ function? If this is not possible, is there a workaround? (C ++ API fixed, so changing the API to a pointer is not possible)

Edit: DataStruct memory will be allocated by C ++ function. Prior to this, I have no idea how big the data array should be. (Thanks for the comments below)

+7
c ++ c # dll
source share
3 answers

I used the following test implementation:

 int API_ReadFile(const wchar_t* filename, DataStruct** outData) { *outData = new DataStruct(); (*outData)->data = (unsigned char*)_strdup("hello"); (*outData)->len = 5; return 0; } void API_Free(DataStruct** pp) { free((*pp)->data); delete *pp; *pp = NULL; } 

C # code to access these functions is as follows:

 [StructLayout(LayoutKind.Sequential)] struct DataStruct { public IntPtr data; public int len; }; [DllImport("ReadFile.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] unsafe private static extern int API_ReadFile([MarshalAs(UnmanagedType.LPWStr)]string filename, DataStruct** outData); [DllImport("ReadFile.dll", CallingConvention = CallingConvention.Cdecl)] unsafe private static extern void API_Free(DataStruct** handle); unsafe static int ReadFile(string filename, out byte[] buffer) { DataStruct* outData; int result = API_ReadFile(filename, &outData); buffer = new byte[outData->len]; Marshal.Copy((IntPtr)outData->data, buffer, 0, outData->len); API_Free(&outData); return result; } static void Main(string[] args) { byte[] buffer; ReadFile("test.txt", out buffer); foreach (byte ch in buffer) { Console.Write("{0} ", ch); } Console.Write("\n"); } 

Data is now transferred to buffer safely, and there should be no memory leaks. I would like this to help.

+5
source share

If you call your own code, make sure your structures are aligned in memory. The CLR does not guarantee alignment unless you click it.

Try

 [StructLayout(LayoutKind.Explicit)] struct DataStruct { string data; int len; }; 

Further information: http://www.developerfusion.com/article/84519/mastering-structs-in-c/

0
source share

There is no need to use unsafe to pass a pointer to an array from a DLL. Here is an example (see the "Results" parameter). The key is to use the ref attribute. It also shows how to transfer several other types of data.

As defined in C ++ / C:

 #ifdef __cplusplus extern "C" { #endif #ifdef BUILDING_DLL #define DLLCALL __declspec(dllexport) #else #define DLLCALL __declspec(dllimport) #endif static const int DataLength = 10; static const int StrLen = 16; static const int MaxResults = 30; enum Status { on = 0, off = 1 }; struct Result { char name[StrLen]; //!< Up to StrLen-1 char null-terminated name float location; Status status; }; /** * Analyze Data * @param data [in] array of doubles * @param dataLength [in] number of floats in data * @param weight [in] * @param status [in] enum with data status * @param results [out] array of MaxResults (pre-allocated) DLLResult structs. * Up to MaxResults results will be returned. * @param nResults [out] the actual number of results being returned. */ void DLLCALL __stdcall analyzeData( const double *data, int dataLength, float weight, Status status, Result **results, int *nResults); #ifdef __cplusplus } #endif 

As used in C #:

 private const int DataLength = 10; private const int StrLen = 16; private const int MaxThreatPeaks = 30; public enum Status { on = 0, off = 1 }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct Result { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = StrLen)] public string name; //!< Up to StrLen-1 char null-terminated name public float location; public Status status; } [DllImport("dllname.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = " analyzeData@32 ")] // "@32" is only used in the 32-bit version. public static extern void analyzeData( double[] data, int dataLength, float weight, Status status, [MarshalAs(UnmanagedType.LPArray, SizeConst = MaxResults)] ref Result[] results, out int nResults ); 

Without the extern "C" part extern "C" ++ compiler would distort the export name depending on the compiler. I noticed that the name of the EntryPoint / Exported function is the same as the function name in a 64-bit DLL, but when compiled into a 32-bit DLL it has the added "@ 32" (the number may change). Run dumpbin /exports dllname.dll to find the exported name. In some cases, you may also need to use the DLLImport parameter ExactSpelling = true . Note that this function is declared by __stdcall . If it was not specified, that would be __cdecl , and you would need CallingConvention.Cdecl .

Here's how to use it in C #:

 Status status = Status.on; double[] data = { -0.034, -0.05, -0.039, -0.034, -0.057, -0.084, -0.105, -0.146, -0.174, -0.167}; Result[] results = new Result[MaxResults]; int nResults = -1; // just to see that it changes (input value is ignored) analyzeData(data, DataLength, 1.0f, status, ref results, out nResults); 
0
source share

All Articles