2

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?

Daniele Nardi
  • 35
  • 1
  • 6
  • 1
    That ref class is pretty borken, the wrapper should be declared as int func2_w(System::String^ s) so it can be easily called from any managed language. Google "convert from system::string to char*" to find the string conversion code you need. – Hans Passant Jul 06 '18 at 12:24

2 Answers2

5

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);
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
0

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.

Daniele Nardi
  • 35
  • 1
  • 6