0

I have a CPP app that I want to invoke to my C# app but I'm having trouble passing a ref string param to the CPP method which accepting std::wstring.

My code as follows:

CPP Header:

namespace NMSP
    {
        extern "C"
            {
                __declspec(dllexport) int MyCPPMethod(std::wstring &StrCode);
            }

CPP Source:

__declspec(dllexport) int NMSP::MyCPPMethod(std::wstring &StrCode)
    {
        StrCode = "12345";
        return 1;
    }

C#:

[DllImport(@"MyExternal.dll", CharSet = CharSet.Unicode)]
static extern int MyCPPMethod(ref string StrCode);

string strVer = "version";
    var rcver = MyCPPMethod(ref strVer);

When accessing the CPP method, I get "Error reading string" error from the std::wstring &StrCode value.

I've been tried using StringBuilder str = new StringBuilder("version", 1024); but no luck.

If I'm changing the std::wstring to char*, I get 'v' (when sending "version" in the parameter) - still I'm confused.

Any help will be appreciated. Thx.

Dave Gahan
  • 299
  • 2
  • 14
  • You can't call this function from C# ever. `std::wstring` cannot be used for interop. Use `wchar_t*`, map to `StringBuilder`, and include a buffer length parameter. – David Heffernan Apr 09 '18 at 08:30
  • 1
    That is not possible, only a C++ compiler knows how to property create and destruct an std::wstring object. Your [DllImport] declaration, without the ref, is equivalent to `wchar_t[]`. You must add an extra parameter so you can pass the length of the array and make it safe with wcscpy_s(). If std::wstring is a hard requirement then only a C++/CLI wrapper can get that job done. – Hans Passant Apr 09 '18 at 08:30
  • David Heffernan - thx. Since I'm newbie with cpp, can you please point me to how to achieve that? Especially the buffer implementation. Hans Passant - thx. Same here, is it possible to show how it looks in a sample => wcscpy_s() ? More updates - still using string (c#) to std::wstring (c++) but added a stdcall convention and now I'm getting the following: When sending "version", I can see in cpp that sent value is "ion". After changing and passing back, the c# value is now "vers12345". Why my first 4 letters are cut? – Dave Gahan Apr 09 '18 at 09:09
  • https://stackoverflow.com/questions/34373402/call-a-wstring-c-method-from-c-sharp – user743414 Apr 09 '18 at 09:35
  • Possible duplicate of [Call a wstring C++ method from C#](https://stackoverflow.com/questions/34373402/call-a-wstring-c-method-from-c-sharp) – user743414 Apr 09 '18 at 09:36
  • Nope, you cannot use `std::wstring`, like we said already. There are hundreds of examples around. We don't need to create yet another. Do some research. – David Heffernan Apr 09 '18 at 12:55
  • Thank you all - at the end we're going through the CLR solution which makes that easier and working perfectly (apart from the .net framework issue I'm dealing with another post). Thanks for your answers. – Dave Gahan Apr 15 '18 at 07:01

0 Answers0