Search code examples
c#stringdllcharhwndhost

Pass string to dll


How to call a function in c++ dll from C# WPF application with string parametrs? I add dll to C# app through "Add References", not "[DLLImport]"

All problem is that C# suggests function with 'sbyte*' parametr, not 'char*'. Functions with 'int' parametrs works perfect.

Here is code:

My function in c++ dll:

public ref class OpenGLHwnd : public HwndHost   
{
public:
    void myFunc(char* name)
    {
        // some code
    }

C# code:

HwndHost host = new WPFOpenGLLib.OpenGLHwnd();
HWNDPlaceholder.Child = host;
(HWNDPlaceholder.Child as WPFOpenGLLib.OpenGLHwnd).myFunc("aaaa");

myFunc want 'sbyte*' parametr, not 'char*'. Why?

Or tell, please, how to convert string to sbyte*


Solution

  • Since your C++ DLL is apparently a .NET assembly (ref class, i.e. C++/CLI), you can just pass the string as .NET String:

    #include <msclr/marshal.h>
    using namespace msclr::interop;
    
    public ref class OpenGLHwnd : public HwndHost   
    {
    public:
        void myFunc(System::String^ name)
        {
            marshal_context^ context = gcnew marshal_context();
            const char* ptr = context->marshal_as<const char*>(name);
            puts(ptr);
            delete context;
        }