如何使用C#程序中的Visual C 编写的DLL
How to use a DLL written in Visual C++ in a C# program?
可能的重复:
C#p Indoke dll没有进入C 的入口点?
在对So和Google进行了相当彻底的冲浪后,我问这个问题,大多数答案使我大约有80%的方式,但仍然有些混乱,因此请告诉我出路。<<<<<<<<<<<<<<<<<</p>
我有一些视觉C 函数定义如下:
mydll.h
#ifdef FUNCTIONS_EXPORTS
#define FUNCTIONS_API __declspec(dllexport)
#else
#define FUNCTIONS_API __declspec(dllimport)
#endif
namespace Functions {
class MyFunctions {
public:
static FUNCTIONS_API int Add(int a, int b);
static FUNCTIONS_API int Factorial(int a);
};
}
mydll.cpp
namespace Functions {
int MyFunctions::Add (int a, int b)
{
return a+b;
}
int MyFunctions::Factorial (int a)
{
if(a<0)
return -1;
else if(a==0 || a==1)
return 1;
else
return a*MyFunctions::Factorial(a-1);
}
}
现在,我想将此构建生成的DLL导入我的C#程序中:
program.cs
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace DLLTester
{
class Program
{
[DllImport("path\to\thedll\myDLL.dll")]
public static extern int Factorial(int a);
static void Main(string[] args) {
int num;
num = int.Parse(Console.ReadLine());
Console.WriteLine("The factorial is " + Factorial(num));
}
}
}
我尝试编写没有类的功能(在定义时没有static
关键字),但是即使是行为并给出错误。
我在哪里出错?
我看到的最大问题是您正在尝试使用P/Indoke类方法。由于C 名称杂交,您提供的DLL中不存在您提供的入口点。您应该能够在DLL上运行dumpbin.exe
并亲自查看。
使用C 类时,我总是遵循在处理C 类创建的C 方面创建" Manager"方法的模式。创建方法创建一个对象(在C 侧),将其存储在数组中,并返回一个整数ID,我用来使用该实例进行进一步调用。本文概述了一种类似的方法,并且还直接使用类实例涵盖(此方法依赖于导入使用单个编译器时应该是确定性的操纵名称)。
我建议浏览名称Mangling文章以及如何用于DllImport
目的,并阅读上一段中链接的大多数Codeproject文章。它写得很好,涵盖了很多P/Indoke Minutiae。
相关文章:
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 不同的Visual Studio版本中缺少.dll
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 在Visual Studio 2017中创建的简单DLL不会在XP中加载
- 为什么在Visual Studio的OpenCV项目中使用/MT时仍然需要dll?
- 从现有源创建 MS Visual C++ DLL 项目
- 如何在不同的visual studio配置中指向正确的DLL
- 静态链接 Visual Studio dll 到动态链接的 sfml 项目
- C++ 使用 SWIG 和 Visual Studio 2017 在 python 中导入 DLL
- 如何处理错误"E1696命令行错误:无法在Visual Studio 2017中打开元数据文件"mscorlib.dll"?
- Visual studio C++ dll reference
- 从Excel VBA调用C++DLL只能从Visual Studio中的调试实例工作
- 外部 "C" Visual Studio 2015 中的显式类型错误,DLL 测试代码
- 如何在没有任何依赖库的情况下在Visual Studio中构建dll?
- 在Visual Studio中调试Qt,缺少msvcp140d_app.dll
- 编译 C++ dll Visual Studio 与 crt 库的链接错误
- 错误: "Unable to find the DLL xyz.dll!" Visual Studio 2010
- 在VC++中创建DLL(Visual Studio 2008)
- 编译某些头文件到DLL (Visual Studio 2010 c++)
- Dependence on msvcr120d.dll Visual Studio 2015 (Intel TBB)