如何在C#/ Python中从DLL调用函数

时间:2016-03-10 10:54:00

标签: c# python c++ dll

我有下一个用于创建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函数。

谢谢

1 个答案:

答案 0 :(得分:0)

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

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

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

另见: