托管C#Win32应用程序的非托管DLL.与课堂入口

Unmanaged DLL to Managed C# win32 application. Entry with Class

本文关键字:DLL 课堂 入口 C#Win32 应用程序 托管      更新时间:2023-10-16

我的问题是试图访问名为函数的类中定义的 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),上面是上面的示例。由于我已经在这里有#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类内部,我不知道该怎么做。

错误是。找不到入口点Add

您非常接近使它起作用,并且您的怀疑是正确的。为了使您的.NET代码插入DLL中,它需要在DLL中找到预期的C型函数符号。由于您的dll是使用C 代码构建的(无论您使用的外部" C",该函数名称都被填充,因此.NET无法找到它的期望。

解决方案

要解决此问题,您的函数声明需要是纯C(并保留围绕这些声明的外部" C")。这意味着没有名称空间,没有类,没有参考等。但是,如果需要,函数实现代码可以为C 。您只需要.NET和您的DLL就可以就声明(接口)达成共识。

建议

出于某种原因,您需要按照它的方式将所有C 代码保留(因为其他代码正在使用),则只需在其顶部创建一个新的薄C层,这将是您使用的DLL公共接口。net。