C#调用C++动态库

1 篇文章 0 订阅

Hello,大家好。今天来介绍一下C#如何调用C++动态库。文章会分两个部分进行讲解。

  • C++如何编写一个动态库

  • C#如何进行调用

C++ 编写动态库

1.创建一个C++动态链接库项目。

2.声明方法

下面分别举例了无入参和有入参的函数。其中有入参的函数列举了int、char* 、和结构体。

#include "stdafx.h"using namespace std;#include<iostream>//无参数extern "C" _declspec(dllexport) void Print(){       cout << "Print" << endl;}//int类型extern "C" _declspec(dllexport) void PrintInt(int i){       cout << i << endl;}
//char* 类型extern "C" _declspec(dllexport) void PrintString(char* str){      cout << str << endl;}
typedef struct TTestStruct{public:       int a;       int b;       int c;public:       TTestStruct() { memset(this, 0, sizeof(TTestStruct)); }}TestStruct, *LtestStruct;
//结构体extern "C" _declspec(dllexport) void ContronStruct(TestStruct testStruct){       if (testStruct.a != NULL)       {              cout << testStruct.a << endl;       }
       if (testStruct.b != NULL)       {              cout << testStruct.b << endl;       }
       if (testStruct.c != NULL)       {             cout << testStruct.c << endl;       }
}

 

3.写完方法之后直接生成动态库

 

C# 调用动态库

 

1.首先将生成的动态库拷贝到C#程序的运行目录下

2.编写调用C++动态库的代码

 

              [DllImport("C++Dll.dll", CallingConvention = CallingConvention.Cdecl,CharSet = CharSet.Ansi)] public static extern void Print();
 [DllImport("C++Dll.dll", CallingConvention = CallingConvention.Cdecl,CharSet = CharSet.Ansi)] public static extern void PrintInt(int a);
  [DllImport("C++Dll.dll", CallingConvention = CallingConvention.Cdecl,CharSet = CharSet.Ansi)]  public static extern void PrintString(string str);
  [DllImport("C++Dll.dll", CallingConvention = CallingConvention.Cdecl,CharSet = CharSet.Ansi)]  public static extern void ContronStruct(TestStruct test);
        public struct TestStruct        {            public int a;            public int b;            public int c;        }               private void button1_Click(object sender, EventArgs e)        {            Print();        }
        private void button2_Click(object sender, EventArgs e)        {            PrintInt(100);        }
        private void button3_Click(object sender, EventArgs e)        {            PrintString("输出字符串");        }
        private void button4_Click(object sender, EventArgs e)        {            TestStruct test = new TestStruct();            test.a = 100;            test.b = 200;            test.c = 300;            ContronStruct(test);        }   
 

3.输出结果

 

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值