这里两个问题,一是如何将C++编译成dll,二是在C++和C#中调用这个dll
1,写C++的dll,参照以下link,它说的是C++中的dll调用,所以肯定成功
http://msdn2.microsoft.com/en-us/library/ms235636(VS.80).aspx
2,写一个C#,调用上面写的dll
2.1将以上的dll拷贝到debug/release目录,然后写C#程序如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MyCSharpExecRefsDll
{
class Program
{
static void Main(string[] args)
{
myWin32 mywin32 = new myWin32();
Console.WriteLine(myWin32.Add(3, 4));
}
public class myWin32
{
[DllImport("MathFuncsDll1.dll")]
public static extern double Add(double a, double b);
[DllImport("MathFuncsDll1.dll")]
public static extern double Subtract(double a, double b);
[DllImport("MathFuncsDll1.dll")]
public static extern double Multiply(double a, double b);
[DllImport("MathFuncsDll1.dll")]
public static extern double Divide(double a, double b);
}
}
}
调用的时候总是说没有这个入口。
Unable to find entry point named "Add" in DLL "MathFuncDll1.dll"
根据网友Lucrefy(LuLuBoy) 的介绍使用depends.exe 察看,也有这个函数但就是找不到。再根据他的介绍,使用比较老的external 而非class的办法,成功。
C++头文件修改如下:
namespace MathFuncs
{
// Returns a + b, export in a old way
extern "C" __declspec(dllexport) double myAdd(double a, double b);
class MyMathFuncs
{
public:
// Returns a + b
static __declspec(dllexport) double Add(double a, double b);
};
}
C#程序如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MyCSharpExecRefsDll
{
class Program
{
static void Main(string[] args)
{
myWin32 mywin32 = new myWin32();
Console.WriteLine(myWin32.myAdd(3, 4));
}
public class myWin32
{
[DllImport("MathFuncsDll1.dll", EntryPoint = "myAdd", CharSet = CharSet.Auto)]
public static extern double myAdd(double a, double b);
}
}
}
3,参考页面
http://community.csdn.net/Expert/topic/5275/5275701.xml?temp=.9875147
4,其他参考页面,以下页面详细讨论了这个问题。
http://www.etro.vub.ac.be/Personal/bjansen/dlls/interfacing.html