Hi,
I am quite new in Viusal C# and I am blocking on something since two days. It might (and I hope so) seem stupid and easy for some.
Well I am using a DLL to get some value from the buffer of a controller card.
The fact is I need to give the address of an array of integer to the DLL, as shown bellow: (C# source)
[
DllImport("C:\\PCI-Dask.dll")] unsafe private static extern int AI_ContReadChannel(int CardNumber, int Channel, int AdRange, int*[] Buffer, int ReadCont, double SampleRate, int SyncMode);
I can not find how to
- declare the DLL function properly, that is do I have to write int*[] Buffer or int *Buffer or anything else Moreover, Visual Studio wants to use this in unsafe mode. Is it hazardous, or not
When I want to use the function, I can not find a proper manner What is the best method to call the function and to insert the address of an array of integer
In case, I give you the source of the C++, which works :
How it is declared:
int__stdcall AI_ContReadChannel (int CardNumber, int Channel, int AdRange,
int *Buffer, int ReadCount, double SampleRate, int SyncMode);
How it is used:
int *ai_buf;
mem_size=data_size * 2;
hMem = GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT,mem_size);
ai_buf = (U16 *)GlobalLock(hMem);
if (ai_buf == NULL ) {
MessageBox(hWnd,"DMA", "No Memory", MB_OK);
SendMessage(hWnd, WM_CLOSE, 0, 0L);
break;
}
GlobalFix(hMem);
AI_ContReadChannel(0, 0, 2, ai_buf, 2000, 10000.0, 2)

How to put the address of an array as a parameter in a DLL function???
Tim McQueen
I have a similar problem. I don't have an answer for you but perhaps someone can answer the question for both of us. My problem is this:
I want to call a C function supplied in a static library (libusb.lib), not a dynamically linked library (.dll) from a C# class.
My application is C# and I need to pass an array of Bytes (as a C pointer to its base) to a C function that resides in the external static library. The use of Import DLL does seem appropriate since it is a static, not dynamic library.
The C function parameter is declared in its .h include file as a char* which is used for both input and output.
I have two questions:
1) How do I call a C function from C#.
2) How do I pass a Byte[] to the C function which expects a char* pointer to an array of native C chars
Thanks for any help
David.
WillyC
Define function by the following way:
private static extern int AI_ContReadChannel(int CardNumber, int Channel, int AdRange, IntPtr Buffer, int ReadCont, double SampleRate, int SyncMode);
Allocate buffer:
IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * n); // n is number of members to allocate
Fill buffer from int[] array using Marshal.Copy:
Mashal.Copy(intArray, 0, buffer, n); // intArray is int[]
Call function:
AI_ContReadChannel(cardNumber, channel, adRange, buffer, readCont, sampleRate, syncMode);
Release unmanaged pointer:
Marshal.FreeHGlobal(buffer);