I inherited a C++ DLL with its related header file, with functions declared like
int func1(int i);
int func2(char* s);
I also inherited a reference VC++ reference class that wraps the above DLL to be used in C# environment
public ref class MyWrapperClass
{
int func1_w(int i)
{
return func1(i);
}
int func2_w(char* s)
{
return func2(s);
}
}
From my C# application, I can use func1_w(int i), but I don't understand how to pass a string to func2_w(sbyte* s): I got an error about I can't get a pointer to an sbyte. I set the C# prject as unsafe and declared the function as unsafe.
How can I pass a sbyte* parameter to functiuon func2_w?
As I've said in the comment, probably the most stupid wrapper I've ever seen. You'll have to allocate the ansi string manually. Two ways:
string str = "Hello world";
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.StringToHGlobalAnsi(str);
// Pass the string, like:
mwc.func2_w((sbyte*)ptr);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
Another way, using Encoding.Default
(but note the special handling for the terminating \\0
)
string str = "Hello world";
// Space for terminating \0
byte[] bytes = new byte[Encoding.Default.GetByteCount(str) + 1];
Encoding.Default.GetBytes(str, 0, str.Length, bytes, 0);
fixed (byte* b = bytes)
{
sbyte* b2 = (sbyte*)b;
// Pass the string, like:
mwc.func2_w(b2);
}
In the end I used the following approach:
sbyte[] buffer = new sbyte[256];
String errorMessage;
fixed (sbyte* pbuffer = &buffer[0])
{
megsv86bt_nips.getLastErrorText(pbuffer);
errorMessage = new string(pbuffer);
};
Someone posted it in the comments of my question, but I can't see it anymore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.