gpt4 book ai didi

c# - 无法让 MFC dll 函数在 .net 中运行

转载 作者:行者123 更新时间:2023-11-28 02:18:01 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的 MFC DLL,导出其函数并在 C# .net 项目中使用在下面的代码中,我在 DLL 中有两种方法,我已经将发帖者的建议用于原始问题。我重新发布当前代码,我收到错误

{ "Unable to find an entry point named '_Worker_Create@0'in DLL 'C:\Users\mspath\Documents\MDS_SIMCA\DevSIMCA_Dll\TestDLL\Debug\MFClib.dll'.":"" }

我已经使用 dumpbin.exe 获得了正确的错位名称。

MFC 动态链接库.cpp

   #include "stdafx.h"
#include "Worker.h"

Worker::Worker(void)
{
}

Worker::~Worker(void)
{
}

int Worker::GetInteger()
{
return 44;
}

int Worker::DoMath(int iOne, int iTwo)
{
return iOne * iTwo;
}

MFC 动态链接库.h

类 worker {民众: worker (无效); ~ worker (无效);

static int GetInteger ();
static int DoMath (int iOne, int iTwo);

};

MFCLib.cpp

extern "C"
{
__declspec(dllexport) void * __stdcall Worker_Create()
{
return new Worker();
}

__declspec(dllexport) void * __stdcall Worker_Destroy(Worker * instance)
{
delete instance;
instance = 0;
return instance;
}

__declspec(dllexport) int __stdcall Worker_DoMath(Worker * instance, int i, int j)
{
return instance->DoMath(i, j);
}
}

C#.net

   public partial class MainWindow : Window
{
/*
* from dumbin.exe /exports:
*
1 0 00011519 _Worker_Create@0 = @ILT+1300(_Worker_Create@0)
2 1 00011230 _Worker_Destroy@4 = @ILT+555(_Worker_Destroy@4)
3 2 000110D2 _Worker_DoMath@12 = @ILT+205(_Worker_DoMath@12)
*/
[DllImport("C:\\Users\\mspath\\Documents\\MDS_SIMCA\\DevSIMCA_Dll\\TestDLL\\Debug\\MFClib.dll",
EntryPoint = "_Worker_Create@0",
ExactSpelling = false,
CallingConvention = CallingConvention.StdCall)]
public extern static IntPtr Worker_Create();

[DllImport("C:\\Users\\mspath\\Documents\\MDS_SIMCA\\DevSIMCA_Dll\\TestDLL\\Debug\\MFClib.dll",
EntryPoint = "_Worker_Destroy@4",
CallingConvention = CallingConvention.StdCall)]
public extern static IntPtr Worker_Destroy(IntPtr iptr);

[DllImport("C:\\Users\\mspath\\Documents\\MDS_SIMCA\\DevSIMCA_Dll\\TestDLL\\Debug\\MFClib.dll",
EntryPoint = "_Worker_DoMath@12",
CallingConvention = CallingConvention.StdCall)]
public extern static int Worker_DoMath(IntPtr instance, int i, int j);

public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
IntPtr instance = Worker_Create();

int i = Worker_DoMath(instance, 4, 2);

Worker_Destroy(instance);
}
}

最佳答案

您必须在 C++ 类的外部声明外部“C 风格”函数。将调用通过管道传递给类的一种方法:

__declspec(dllexport) int DoMath (int iOne, int iTwo)
{
Worker* worker = new Worker();
int i = worker-> DoMath(iOne, iTwo);
delete worker;
return i;
}

或者将您的 C++ 类转换为 C++/CLI 类,并将库导入为托管 库而不是非托管 库。

免责声明:我的 C++ 生锈了,所以我可能在语法和/或适当的内存管理上略有偏差。

关于c# - 无法让 MFC dll 函数在 .net 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33437032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com