c#调用c++生成dll文件中的类方法

首先得有一个c++程序,我们这里叫test.
其中代码
test.h
{


class MyMath
{
public:
__declspec(dllexport) float Mysub(float a, float b);
};


}
 


test.cpp
{
#include "stdafx.h"
#include "test.h"


extern "C"__declspec(dllexport) float MyAdd(float a, float b)
{


return (a + b);
}


 float MyMath::Mysub(float a, float b)
{
return a - b;
}


}




test.def
{
LIBRARY
EXPORTS 
Mysub @1
MyAdd @2


}(注:这个文件很重要,如果没有的话,在c#中调用类中的函数sub的时候,就会找不到sub入口点,不过还有一种解决方法,就是EntryPoint="?Mysub@MyMath@@QAEMMM@Z".其中引号中的内容可以在test.exp文件中找到。)
但是如果有这个文件的话就可以省去找EntryPoint那里引号中的内容。








然后我们有一个c#程序,我们这里叫dlltest.
其中代码
新建了一个类MyMath.cs(名字不重要),它主要是为了接受c++中的方法,这样在c#通过这个类找到那些方法就比较方便了。




MyMath.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace dlltest
{
    class MyMath
    {
        [DllImport("test.dll", EntryPoint = "Mysub")]
        public static extern float Mysub(float a,float b);


        [DllImport("test.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "MyAdd")]
       
        public static extern float MyAdd(float a,float b);
        
    }
}


}




主函数Program.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
 
{
     
    class Program
    {
 
         
      
            static void Main(string[] args)
            {
              Console.WriteLine(MyMath.MyAdd(1, 2));
              Console.WriteLine(MyMath.Mysub(5,1));
              Console.ReadKey();


            }


}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值