欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#调用C++动态库

程序员文章站 2022-07-14 09:38:08
...

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

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

  • C#如何进行调用

C++ 编写动态库

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

C#调用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#程序的运行目录下

C#调用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.输出结果

 

C#调用C++动态库

上一篇: C#调用C++动态库

下一篇: crypto