【问题标题】:how to call function from DLL in C#/Python如何在 C#/Python 中从 DLL 调用函数
【发布时间】:2016-03-10 10:54:00
【问题描述】:

我有下一个用于创建 DLL 文件的 C++ 代码

// 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));
        }
    }
}

但收到此消息 error img

或在python代码中

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/RFC/testDLL.py", line 6, in <module>
    result1 = mydll.Add(10, 1)
  File "C:\Python27\lib\ctypes\__init__.py", line 378, in __getattr__
    func = self.__getitem__(name)
  File "C:\Python27\lib\ctypes\__init__.py", line 383, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'Add' not found

请帮忙 如何修复此代码,并调用例如 ADD 函数。

谢谢

【问题讨论】:

    标签: c# python c++ dll


    【解决方案1】:

    由于您正在编译的是 C++,因此导出的符号名称将为 mangled

    您可以通过查看 DLL 的导出列表来确认这一点,使用类似 DLL export viewer 的工具。

    当您打算通过 FFI 调用 DLL 时,最好提供从 DLL 导出的纯 C 语言。您可以使用extern "C" 来为您的 C++ 方法编写一个包装器。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      相关资源
      最近更新 更多