Reputation: 167
I am implementing c#.net wrapper for C-based Library. currently, working on function with passing A void pointer, which will set value.
NOTE : void pointer can take different data type depending on Enum.
Objective: to pass void pointer and set value
I checked many solutions to implement and finally came to following state :
The C-dll function:
int function_call(enum a, void * var);
The C function call code:
char name[255];
name = "asd";
function_call(enum a, &name);
The C# wrapper code:
[DllImport("mylibrary.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int function_call(enum a, IntPtr var);
The C# function call code:
IntPtr name;
string val = "asd";
name = Marshal.StringToHGolbalUni(val);
int ret = function_call(Enum_type, name);
By this method it only sets First character
a
from the inputasd
.
I have already checked "Duplicate" questions but doesnt solve the issue:
How to declare void pointer in C#
Upvotes: 0
Views: 2505
Reputation: 167
The Issue was resolved with :
[DllImport("mylibrary.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
and
name = Marshal.StringToHGolbalAnsi(val);
On client side :
IntPtr nameptr;
string name = "asd";
nameptr= Marshal.StringToHGlobalAnsi(name);
Upvotes: 0
Reputation: 2556
I would treat your void *
as a char *
and use
[MarshalAs(UnmanagedType.LPStr)] StringBuilder var
instead of IntPtr
You should find it works as expected, but take care with size of the char array that your C function expects. Perhaps an explicit size in your declaration of your StringBuilder variable before you call the C function like this:
StringBuilder newvar= new StringBuilder(512);
Good link explaining the circumstances where StringBuilder is used instead of String or IntPtr is explained here - Thanks Amy for the link
Upvotes: 3