在C#中调用C++写的DLL

这里两个问题,一是如何将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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值