最近项目需求需要将qt写的动态库给c#项目调用,所以就在网上查了一些资料,准备先从C#调用c++接口开始。我没有从事过c#开发,对于c#的学习也只是大学时候学过一点现在都忘得差不多了。首先从C++接口开始。
因为我是从事qt开发的,所以用qtcreator写代码比较习惯,当然写c++代码大家习惯用什么写都行,vs2015,dev c++,vc++6.0都行,这里我只是用QtCreator做一个示范。
用QtCreator写了一个简单的C++的动态库,对于的文件如下:
工程文件:
QT -= gui
TEMPLATE = lib
DEFINES += CPPLIB_LIBRARY
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
cpplib.cpp
HEADERS += \
cpplib.h
# Default rules for deployment.
unix {
target.path = /usr/lib
}
!isEmpty(target.path): INSTALLS += target
头文件:
#ifndef CPPLIB_H
#define CPPLIB_H
#define EXPORT __declspec(dllexport)
extern "C" EXPORT int add(int a, int b);
#endif // CPPLIB_H
CPP:
#include "cpplib.h"
int add(int a, int b) {
return a + b;
}
很简单的一个动态库,里面就一个方法add,计算两数之和。然后构建生产对应的动态库cpplib.dll。接下来是对应的C#调用部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class Program
{
[DllImport("cpplib.dll", EntryPoint = "add", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int a, int b);
static void Main(string[] args)
{
Console.WriteLine("add={0}", add(1, 2));
Console.ReadKey();
}
}
}
我c#了解的比较少,这些都是现查的,注意DllImport这个方法要引入using System.Runtime.InteropServices,[DllImport("cpplib.dll", EntryPoint = "add", CallingConvention = CallingConvention.Cdecl)]表示加载动态库cpplib.dll里面的add方法。记住要将生成的动态库文件放到c#对应执行文件目录下,然后点击运行:
可以看到调用成功了。
易错点:1.动态库和对应C#执行文件的位置:
2.Debug和Release之类的参数要对应上,比如我的动态库是64位debug版的,对应C#工程的参数也要一致,比如给其他项目用要标明这些参数: