I have a lib file need to use in c#, I have wrapped it into dll, but when I call one of the function, it always show me the error of "attempted to read or write protected memory".
the function in lib header file is as the following
LONG WINAPI mdRandREx( LONG, LONG, LONG, LPVOID, LPVOID, LONG );
In c++ I wrapped it as the following
long MmdRandREx(long path,long netno,long stno,long dev[],short *buf,long bufsize)
{
buf=(short *)malloc(bufsize);
return mdRandREx(path,netno,stno,dev,buf,bufsize);
}
in c# I import it
[DllImport(@dllname, CallingConvention = CallingConvention.Cdecl)]
static extern long MmdRandREx(long path, long netno, long stno, long[] dev, out short buf, long bufsize);
and call it
short buf;
long retval=MmdRandREx(path,1, stanoPLC, dev1,out buf, bufsize);
I need to use this function to read PLC input and another function to write PLC access a PCI card.
can any one help me on this?
thanks in advance.
Loading
VulpesPosted Dec 9, 2014, 6:32 AM
The short type is 2 bytes in C/C++/C# so you have the right type there. However, as it's a pointer to a buffer I'd have thought that it would be expecting an array of shorts rather than a scalar short (albeit as an 'out' parameter).
I'm also a bit worried about the dev parameter. If you pass that as an int array how will the unmanaged function know what its length is?
One other possible problem is the calling convention. I see the unmanaged function is using WINAPI (typically StdCall on Windows) whereas you're using Cdecl. For consistency, I'd change to Winapi.
So, taking all that into account and hoping for the best with the int[], I'd try:
[DllImport(@dllname, CallingConvention = CallingConvention.Winapi)]
static extern int MmdRandREx(int path, int netno, int stno, int[] dev, [In, Out] short[] buf, int bufsize);
and call with:
short[] buf = new short[bufsize/2]; // assuming bufsize is in bytes not elements
int retval = MmdRandREx(path, 1, stanoPLC, dev1, buf, bufsize);
Sunny WangPosted Dec 10, 2014, 3:24 AM