如何在 C#/Python 中从 DLL 调用函数
how to call function from DLL in C#/Python
我有接下来C++代码来创建
DLL文件// MathFuncsDll.h
#ifdef MATHFUNCSDLL_EXPORTS
#define MATHFUNCSDLL_API __declspec(dllexport)
#else
#define MATHFUNCSDLL_API __declspec(dllimport)
#endif
namespace MathFuncs
{
// This class is exported from the MathFuncsDll.dll
class MyMathFuncs
{
public:
// Returns a + b
static MATHFUNCSDLL_API double Add(double a, double b);
// Returns a - b
static MATHFUNCSDLL_API double Subtract(double a, double b);
// Returns a * b
static MATHFUNCSDLL_API double Multiply(double a, double b);
// Returns a / b
// Throws const std::invalid_argument& if b is 0
static MATHFUNCSDLL_API double Divide(double a, double b);
};
}
// MathFuncsDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
return a / b;
}
}
编译后我有dll文件我想调用例如 ADD 函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace call_func
{
class Program
{
[DllImport("MathFuncsDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern double MyMathFuncs::Add(double a, double b);
static void Main(string[] args)
{
Console.Write(Add(1, 2));
}
}
}
但收到此消息错误图像
或在 Python 代码中
Traceback (most recent call last):
File "C:/Users/PycharmProjects/RFC/testDLL.py", line 6, in <module>
result1 = mydll.Add(10, 1)
File "C:Python27libctypes__init__.py", line 378, in __getattr__
func = self.__getitem__(name)
File "C:Python27libctypes__init__.py", line 383, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'Add' not found
请帮忙我如何修复此代码,并调用例如 ADD 函数。
谢谢
由于它是
您正在编译的C++,因此导出的符号名称将被破坏。
您可以通过查看 DLL 的导出列表,使用 DLL 导出查看器等工具确认这一点。
当您打算通过 FFI 调用 DLL 时,最好从 DLL 提供纯 C 导出。您可以使用extern "C"
围绕C++方法编写包装器来执行此操作。
另请参阅:
- 为面向对象的C++代码开发 C 包装器 API
相关文章:
- 从DLL中删除类的实例
- 从 wxWidgets 中的.DLL加载图标
- Dll在同一解决方案中从 c# 项目导入到 c++ 项目
- 如何在C++非托管/本机 DLL 中从注册免费 COM C# 托管 DLL 创建 COM 对象
- 如何在 C++ 中从 dll 实例化类?
- 如何在运行时从 c++ 中的 DLL 文件创建对象?
- 我们如何从 C# 中的 DLL 中获取C++所有方法?
- 在 Python ctype 中从 C++ DLL 传递向量
- 从.dll中调用.lib in C
- 如何在 c++ 生成器 6 中从应用程序源代码创建 dll
- 将 std::cout 从单独线程中的 DLL 重定向到 QTextEdit
- 如何在Go中从DLL的导出函数中获取std::字符串
- 从 DLL 字符串表中获取字符串
- 在LabVIEW中向DLL传递复数和从DLL传递复数
- 从 dll 中的函数返回时堆损坏
- 如何在C++中从DLL到调用应用程序进行通信
- 在C++中从dll调用sqrt.访问违规
- 如何在 C#/Python 中从 DLL 调用函数
- 在Qt中从dll创建WinForm
- 如何在c++中从dll调用设计时未知的函数