Ahh, hold on.
That is correct as far as correctly passing a string in is concerned (always free the memory afterwards). If you want to receive the string back, then thats a different story I think.
The way I do it is to allocate a buffer to hold the returned string:
string message = string.Empty;
byte[] messageBuffer = new byte[MESSAGE_SIZE];
GCHandle hMessageBuffer = GCHandle.Alloc(messageBuff
IntPtr pMessageBuffer = hMessageBuffer.AddrOfPinne
MarshalledFunctionCall(pMe
message = Marshal.PtrToStringAnsi(pM
hMessageBuffer.Free();
// message now holds a normal .NET string
There are other ways of doing this I'm sure, but this works fine for me.
If you want to pass a string into a function, have it modified and then read it back as an out parameter, then the solution is somewhere near to my first post, but exactly what it is I can't say - I never had that situation. Maybe you can write another C function in the lib to get around that situation and use 2 pointers instead of 1.
Good luck!
Main Topics
Browse All Topics





by: DaeljanPosted on 2006-05-03 at 06:10:20ID: 16595760
Change the import to use:
nsi("testS tring");
estString) ;
tString); // Dont forget to do this!!
IntPtr pPort
instead of
char pszPort
Then, to pass the string to the function:
string testString = "TextBeforeCall";
IntPtr pTestString = Marshal.StringToCoTaskMemA
WkbOpen(pTestString);
Look at alternatives to StringToCoTaskMemAnsi() if this gives you problems.
To retrieve text returned from an IntPtr:
string textAfterFunctionCall = Marshal.PtrToStringAnsi(pT
Marshal.FreeCoTaskMem(pTes
To specify null, use IntPtr.Zero
Be carefull of HWKBENTRY. I don't know what it is, but if you get the type wrong, your stack will go out of line.