如何使用C#程序中的Visual C 编写的DLL

How to use a DLL written in Visual C++ in a C# program?

本文关键字:DLL Visual 程序 何使用      更新时间:2023-10-16

可能的重复:
C#p Indoke dll没有进入C 的入口点?

在对So和Google进行了相当彻底的冲浪后,我问这个问题,大多数答案使我大约有80%的方式,但仍然有些混乱,因此请告诉我出路。<<<<<<<<<<<<<<<<<</p>

我有一些视觉C 函数定义如下:


mydll.h

#ifdef FUNCTIONS_EXPORTS
#define FUNCTIONS_API __declspec(dllexport) 
#else
#define FUNCTIONS_API __declspec(dllimport) 
#endif
namespace Functions {
    class MyFunctions {
    public:
        static FUNCTIONS_API int Add(int a, int b);
        static FUNCTIONS_API int Factorial(int a);
    };
}

mydll.cpp

namespace Functions {
    int MyFunctions::Add (int a, int b)
    {
        return a+b;
    }
    int MyFunctions::Factorial (int a)
    {
        if(a<0)
            return -1;
        else if(a==0 || a==1)
            return 1;
        else
            return a*MyFunctions::Factorial(a-1);
    }
}

现在,我想将此构建生成的DLL导入我的C#程序中:

program.cs

using System;
using System.Collections.Generic;    
using System.Runtime.InteropServices;
namespace DLLTester
{
    class Program
    {
        [DllImport("path\to\thedll\myDLL.dll")]
        public static extern int Factorial(int a);
        static void Main(string[] args) {
            int num;
            num = int.Parse(Console.ReadLine());
            Console.WriteLine("The factorial is " + Factorial(num));
        }
    }
}

我尝试编写没有类的功能(在定义时没有static关键字),但是即使是行为并给出错误。

我在哪里出错?

我看到的最大问题是您正在尝试使用P/Indoke类方法。由于C 名称杂交,您提供的DLL中不存在您提供的入口点。您应该能够在DLL上运行dumpbin.exe并亲自查看。

使用C 类时,我总是遵循在处理C 类创建的C 方面创建" Manager"方法的模式。创建方法创建一个对象(在C 侧),将其存储在数组中,并返回一个整数ID,我用来使用该实例进行进一步调用。本文概述了一种类似的方法,并且还直接使用类实例涵盖(此方法依赖于导入使用单个编译器时应该是确定性的操纵名称)。

我建议浏览名称Mangling文章以及如何用于DllImport目的,并阅读上一段中链接的大多数Codeproject文章。它写得很好,涵盖了很多P/Indoke Minutiae。