How to correctly call methods from unmanaged C++ DLL in C#? -


i have acquisition board controlled c++ api. want call methods directly c# application.

these methods cause problems:

dll:

// read data of board spinapi int pb_get_data(unsigned int num_points, int *real_data, int *imag_data); // write plain ascii file data returned pb_get_data(..) spinapi int pb_write_ascii(const char *fname, int num_points, float sw, float sf, const int *real_data, const int *imag_data); 

where spinapi defined follows:

#ifdef __windows__ #ifdef dll_exports  #define spinapi __declspec(dllexport) #else #define spinapi __declspec(dllimport) #endif #else #define spinapi #endif 

c#:

[dllimport(@"c:\spincore\spinapi\lib32\spinapi.dll", callingconvention = callingconvention.cdecl)] public static extern int pb_get_data(uint num_points, [marshalas(unmanagedtype.lparray)] ref int[] real_data, [marshalas(unmanagedtype.lparray)] ref int[] imag_data);  [dllimport(@"c:\spincore\spinapi\lib32\spinapi.dll", callingconvention = callingconvention.cdecl)] public static extern int pb_write_ascii(string fname, int num_points, float sw, [marshalas(unmanagedtype.lparray)] ref int[] real_data, [marshalas(unmanagedtype.lparray)] ref int[] imag_data); 

when calling pb_get_data(),

pb_get_data((uint)numberofpoints, ref idata, ref idata_imag); 

i following error:

system.accessviolationexception unhandled  message: unhandled exception of type 'system.accessviolationexception' occurred in unknown module. additional information: attempted read or write protected memory. indication other memory corrupt. 

when calling pb_write_ascii(),

pb_write_ascii(@"data\direct_data_0.txt", numberofpoints, (float)actualsw, ref idata, ref idata_imag); 

where:

int[] idata = new int[max_number_points]; int[] idata_imag = new int[max_number_points]; 

nothing happens (the file not written).

does have idea i'm doing wrong , how correct problems? mention call other methods dll.

according hans passant, eliminating ref keyword causing problem. removing resolved issue.


Comments