C#调用C++接口

作者:追风剑情 发布于:2020-6-28 18:01 分类:C#

一、VS新建C++空项目

555.png

CTestDll.h

  1. #ifndef __CTEST_DLL_H
  2. #define __CTEST_DLL_H
  3. // 声明为C编译、链接方式为外部函数
  4. extern "C" _declspec(dllexport) int _cdecl add(int* x, int* y);
  5. extern "C" _declspec(dllexport) int _cdecl sub(int x, int y);
  6. #endif

CTestDll.cpp

  1. #include "CTestDll.h"
  2.  
  3. #ifdef __cplusplus //如果是cpp文件
  4. extern "C" //这部分代码按C编译
  5. {
  6. int add(int* x, int* y)
  7. {
  8. return *x + *y;
  9. }
  10.  
  11. int sub(int x, int y)
  12. {
  13. return x - y;
  14. }
  15. }
  16. #endif

可能会出现的报错

1111.png

重定义解决方法 (调用约定要与代码中写的一致)

2222.png

33333.png

不兼容解决方法

4444.png

二、VS新建C#控制台项目
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.InteropServices;
  7.  
  8. namespace ConsoleApp6
  9. {
  10. class Program
  11. {
  12. [DllImport(@"Dll4.dll", EntryPoint = "add", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
  13. public static extern int add(ref int x, ref int y);
  14. [DllImport(@"Dll4.dll", EntryPoint = "sub", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
  15. public static extern int sub(int x, int y);
  16.  
  17. static void Main(string[] args)
  18. {
  19. int x = 6, y = 5;
  20. int a = add(ref x, ref y);
  21. int b = sub(x, y);
  22. Console.WriteLine("a={0}, b={1}", a, b);
  23. Console.Read();
  24. }
  25. }
  26. }
将C项目编译成dll并拷到bin\x64\Debug下面(即,与C#生成的exe文件同目录)

注意,64位的C#项目无法调用32位的DLL,这里的测试工程统一编译成64位

运行测试

6666.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号