Passing a string variable as a ref between a c# dll and c++ dll

后端 未结 2 553
失恋的感觉
失恋的感觉 2021-01-13 23:01

I have a c# dll and a c++ dll . I need to pass a string variable as reference from c# to c++ . My c++ dll will fill the variable with data and I will be using it in C# how c

相关标签:
2条回答
  • 2021-01-13 23:42

    Pass a fixed size StringBuilder from C# to C++.

    0 讨论(0)
  • 2021-01-13 23:54

    As a general rule you use StringBuilder for reference or return values and string for strings you don't want/need to change in the DLL.

    StringBuilder corresponds to LPTSTR and string corresponds to LPCTSTR

    C# function import:

    [DllImport("MyDll.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static void GetMyInfo(StringBuilder myName, out int myAge);
    

    C++ code:

    __declspec(dllexport) void GetMyInfo(LPTSTR myName, int *age)
    {
        *age = 29;
        _tcscpy(name, _T("Brian"));
    }
    

    C# code to call the function:

    StringBuilder name = new StringBuilder(512);
    int age; 
    GetMyInfo(name, out age);
    
    0 讨论(0)
提交回复
热议问题