I am currently building a project that makes use of DllImport in C# to call a method in a C++ dll.
The method I am trying to call is defined as follows:
extern "C" TESTSYSTEM BSTR setLSystem1(BSTR& i_settings)
I believe i_settings is a file path to a file in the project containing the DLL.
I am trying to call this method in C# using this code:
public static class DllWrapper
{
[DllImport("path/to/dll/dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
[return: MarshalAs(UnmanagedType.BStr)]
public static extern string setLSystem1([MarshalAs(UnmanagedType.BStr)] ref string s);
public static void SetLSystem(string s)
{
var res = setLSystem1(ref s);
}
}
Though when I call SetLSystem, I get the following error:
System.Runtime.InteropServices.SEHException: ‘External component has thrown an exception.’
I have also tried to run this version of the code removing the ref keyword:
public static class DllWrapper
{
[DllImport("path/to/dll.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
[return: MarshalAs(UnmanagedType.BStr)]
public static extern string setLSystem1([MarshalAs(UnmanagedType.BStr)] string s);
public static void SetLSystem(string s)
{
var res = setLSystem1(s);
}
}
though that produces:
System.AccessViolationException: ‘Attempted to read or write protected memory. This is often an indication that other memory is corrupt.’
Unfortunately both errors are quite vague, and I am not very familiar with c++, and can’t find much information online about passing strings from C# as BSTR or BSTR& to c++. Does anyone have any guidance as to how to achieve this?