C#调用C++接口

最近项目需求需要将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#工程的参数也要一致,比如给其他项目用要标明这些参数:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值