我使用P / Invoke,而不是C ++ / CLI,并且正在Visual Studio 2017上工作。
我的应用程序是WPF.NET – 32位,用C#编写。当我在PCx64上运行该应用程序时,该应用程序成功加载了其32位DLL,但当我在虚拟机(64或32)上运行该应用程序时,该应用程序崩溃了。我认为无法添加DLL ...也不知道为什么。
我的DLL是用C ++编写的,包括一个类,其中一些函数是在汇编程序上编写的。可能是问题所在吗?
MyClass.cpp:
int MyClass::Foo_1()
{
__asm
{
mov eax, 0
}
}
void MyClass::SetFoo_1()
{
resultEAX = new int;
int a = -1;
try
{
a = Foo_1();
}
catch (int e) { }
if (a == 0) {
*resultEAX = 0;
}
else {
*resultEAX = 1;
}
}
MyClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
class __declspec(dllexport) MyClass {
public:
int * resultEAX ;
int Foo1();
void SetFoo_1();
int GetEAX();
};
#endif
MyClassCaller.h:
extern "C" {
#endif
__declspec(dllexport) MyClass* Create();
__declspec(dllexport) void Dispose(MyClass* a_pObject);
__declspec(dllexport) void SetFoo_1(MyClass* a_pObject);
__eclspec(dllexport) int GetEAX(MyClass* a_pObject);
#ifdef __cplusplus
}
#endif
MyClassCaller.cpp:
Graphics* Create()
{
return new MyClass();
}
void Dispose(MyClass * a_pObject)
{
if (a_pObject != NULL)
{
delete a_pObject;
a_pObject = NULL;
}
}
void SetFoo_1(MyClass * a_pObject)
{
if (a_pObject != nullptr)
{
a_pObject->SetFoo_1();
}
}
int GetEAX(MyClass * a_pObject)
{
if (a_pObject != NULL)
{
return a_pObject->GetEAX();
}
return 0;
}
然后我使用托管的C#代码从WPF.NET调用该类:
IntPtr pMyClass = MyClassHandling.Create();
Int32 a = 0;
Int64 b = 0;
long c = 0;
long rslt = 0;
try
{
MyClassHandling.SetFoo_1(pMyClass);
if (Environment.Is64BitOperatingSystem)
{
//"SysWOW64"
b = MyClassHandling.GetEAX(pMyClass);
//……
}
else
{
//"system32"
a = pMyClassHandling.GetEAX(pGraphics);
//…
}
MyClassHandling.Dispose (pGraphics);
pMyClass = IntPtr.Zero;
[DllImport("SomeAssemblerFunctions.dll")]
static public extern IntPtr Create();
[DllImport("SomeAssemblerFunctions.dll")]
static public extern void Dispose(IntPtr pGraphicsObject);
[DllImport("SomeAssemblerFunctions.dll", EntryPoint = "SetGraphicMode1")]
static public extern void SetFoo_1(IntPtr pGraphicsObject);
[DllImport("SomeAssemblerFunctions.dll", EntryPoint = "GetEAX")]
static public extern int GetEAX(IntPtr pGraphicsObject);