DllImport StackOverflowException
I'm trying to use C++ DLL(borland c builder) from c#. Function writeParameter works fine, it writes correct data to a file, but then i have an exception "An unhandled exception of type 'System.StackOverflowException' occurred in PresentationFramework.dll"
C++ code:
#include <vcl.h>
#include <windows.h>
#include <fstream.h>
#pragma hdrstop
#pragma argsused
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved)
{
return 1;
}
//---------------------------------------------------------------------------
#pragma pack (push,1)
typedef struct
{
int a;
}ABC;
#pragma pack (pop)
//---------------------------------------------------------------------------
extern "C" void __declspec(dllexport) __cdecl writeParameter(ABC *abc)
{
ofstream outfile("result.txt");
outfile<< "A=" <<endl;
outfile << abc->a <<endl;
outfile.close();
}
c#:
[StructLayoutAttribute(LayoutKind.Sequential)]
public class ABC
{
public int a;
}
[DllImport("D:\\monitorVC.dll", EntryPoint = "_writeParameter", CallingConvention = CallingConvention.Cdecl, CharS开发者_StackOverflow中文版et = CharSet.Ansi)]
public static extern void WriteParameter(
[In,MarshalAs(UnmanagedType.LPStruct)]
ABC abc
);
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
var abc = new ABC() {a = 123};
WriteParameter(abc);
}
Read this blog post about the very poorly chosen name for UnmanagedType.LPStruct and how it does not do what everybody thinks it does. Fix your declaration like this:
[DllImport(...)]
public static extern void WriteParameter([In] ref ABC abc);
class != struct in C#.
Also, the packing of your structure is not the same between the C# version and the C++ version.
I know that it's been a while since this question was posted but I had the same experience trying to load to a VS2010 C# project, a .dll built with CodeGear C++ Builder 2007.
The work-around was to remove all TForms from my .dll. It seemed to me that the exported symbols from these forms (which by the way I could not remove) where "leading" the loader to a stack overflow.
Regards.
精彩评论