I was going to call an unmanaged function in a c library from c#, but it crashed. While troubleshooting I narrowed it down to std::wstring. A minimal example looks like this:
C
#include <iostream>
extern "C" __declspec(dllexport) int __cdecl Start()
{
std::wstring test = std::wstring(L"Hello World");
return 2;
}
C#
using System.Runtime.InteropServices;
internal class Program
{
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Start();
static void Main(string[] args)
{
var result = Start();
Console.WriteLine($"Result: {result}");
}
}
This gives me a Stack overflow. If I remove the line with std::wstring
or I change it to std::string
, there is no problem and I get back 2.
Can anyone explain to me what is going on here?
CodePudding user response:
This is something I noticed:
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
Exporting functions from an EXE instead of a DLL isn't standard. (I think it can be done, but I wouldn't recommend it.)
Build your C code as a DLL instead of an EXE. Statically link the DLL with the C runtime libraries to avoid missing dependency issues that could arise from not having the right DLLs in the loader search path.