【问题标题】:Unmanaged DLL to Managed C# win32 application. Entry with Class非托管 DLL 到托管 C# win32 应用程序。带类进入
【发布时间】:2016-12-05 02:22:14
【问题描述】:

我的问题是试图访问一个名为 function 的类中定义的 dll 函数。

namespace MathLibrary
{
extern "C" 
{
    __declspec(dllexport) double Functions::Add(double a, double b)
    {
        return a + b;
    }

    __declspec(dllexport) double Functions::Multiply(double a, double b)
    {
        return a * b;
    }

    __declspec(dllexport) double Functions::AddMultiply(double a, double b)
    {
        return a + (a * b);
    }
}

}

这就是我从 C++ 中创建的 MathLibrary.dll 现在我想在 C# 中使用它,所以我尝试了 PInvoke 方法。我不知道这叫什么程序,请告诉我我错了。

class Program
{
    [DllImport("MathLibrary.dll", CallingConvention =        CallingConvention.Cdecl)]
    public static extern double Add(double a, double b);

    static void Main(string[] args)
    {
        double myNumber = Add(10, 5); <- this is the Line. I suspect that it is because the Add is inside a class name Functions that I why I can't Access it and having error that there is no Entry point for the method Add.

        Console.WriteLine(myNumber);
    }
}

MathLibrary.h 看起来像这样,我什至不知道是否仍然需要在 MathLibrary.cpp 上添加 __declspec(dllexport),例如上面的示例。因为我在这里已经为 dllexport 设置了#ifdef。

#pragma once

#ifdef MATHLIBRARY_EXPORTS  
#define MATHLIBRARY_API __declspec(dllexport)   
#else  
#define MATHLIBRARY_API __declspec(dllimport)   
#endif  

namespace MathLibrary
{
// This class is exported from the MathLibrary.dll  
class Functions
{
public:
    // Returns a + b  
    static MATHLIBRARY_API double Add(double a, double b);

    // Returns a * b  
    static MATHLIBRARY_API double Multiply(double a, double b);

    // Returns a + (a * b)  
    static MATHLIBRARY_API double AddMultiply(double a, double b);
};
}

所以回到问题。我怀疑我必须从 PInvoke 或 DLLImport 定义 DLL 函数,该方法位于 Function CLass 内,我不知道该怎么做。

错误是。找不到入口点Add。

【问题讨论】:

    标签: c# c++ dll


    【解决方案1】:

    你已经接近让它工作了,你的怀疑是正确的。为了让您的 .NET 代码 PInvoke 到 DLL 中,它需要在您的 DLL 中找到预期的 C 样式函数符号。由于您的 DLL 是使用 C++ 代码构建的(不管您拥有的 extern "C" 是什么),因此函数名称被破坏,因此 .NET 无法找到它所期望的。

    解决方案

    要解决此问题,您的函数 声明 需要是纯 C(并在这些声明周围保留 extern "C")。这意味着没有命名空间、没有类、没有引用等。但是,如果您愿意,函数实现代码可以是 C++。您只需要 .NET 和您的 DLL 就声明(接口)达成一致。

    建议

    如果由于某种原因您需要保持所有 C++ 代码的原样(因为其他代码正在使用它),那么只需在其上创建一个新的薄 C 层,这将是您的 DLL 使用的公共接口。网。

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多