C#调用自身写的类库,只需添加引用,找到DLL那个文件即可,但是用C++写的DLL,就只能用DllImport的方式了,该方式需要引入命名空间
using System.Runtime.InteropServices;下面,新建一个C++的project,右键属性-->
在头文件中键入以下一个测试方法
#pragma once
#define Cplusplus_API extern "C" __declspec(dllexport)
class UsbOperator
{
public:
UsbOperator(void);
public:
~UsbOperator(void);
};
Cplusplus_API int TestAdd(int a,int b);
#define Cplusplus_API extern "C" __declspec(dllexport)
class UsbOperator
{
public:
UsbOperator(void);
public:
~UsbOperator(void);
};
Cplusplus_API int TestAdd(int a,int b);
然后在cpp文件中实现该方法
1 #include "StdAfx.h"
2
3 UsbOperator::UsbOperator(void)
4 {
5 }
6
7 UsbOperator::~UsbOperator(void)
8 {
9 }
10
11 int TestAdd(int a,int b){return a+b;}
2
3 UsbOperator::UsbOperator(void)
4 {
5 }
6
7 UsbOperator::~UsbOperator(void)
8 {
9 }
10
11 int TestAdd(int a,int b){return a+b;}
在生成的这个DLL拷贝到C#生成的BIN目录下面[其他方式略去]
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5
6 namespace UsbAccessAPI
7 {
8 public class UsbAccessAPI
9 {
10
11
12
13 [DllImport("UsbCheck.dll",
14 EntryPoint = "TestAdd",
15 CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
16 public static extern int TestAdd(int a,int b);
17 }}
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5
6 namespace UsbAccessAPI
7 {
8 public class UsbAccessAPI
9 {
10
11
12
13 [DllImport("UsbCheck.dll",
14 EntryPoint = "TestAdd",
15 CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
16 public static extern int TestAdd(int a,int b);
17 }}
此外,在VS的命令行里面输入depends.exe,可以拖入DLL文件,查看UsbCheck.dll中暴露在外的方法接口,
如果你在新建的C++ library中有引用了其他的library的DLL,需要将其他.lib和DLL文件全部拷贝到C#的BIN目录下面来,不然在编译时不会出问题,运行时出现错误又无处DEBUG会郁闷死你的,呵呵,一篇造轮子的文章,留个纪念给自己,呵呵
浙公网安备 33010602011771号