大大大大大大猩猩

导航

C++ 与 C#混合编程 示例 (基于VS2022)

C#使用过程中经常会遇到和C++联合开发的过程,通过C++编写动态库,封装成dll后再C#中调用,在此做个记录,

一、新建C#控制台项目

打开VisualStudio,新建一个C#控制台项目,

image

 

项目名称HelloWorldTest

image

 下一步

image

 

点击下一步,一个默认c#项目创建完成

 

二、创建C++库

在解决方案上右键--添加--新建项目,建一个C++动态链接库工程,

image

 

输入项目名称HelloDll,然后下一步

image

 

创建完成后如下,在 项目--右键--添加--类, 添加 TestDll 头文件 和源文件 ,文件内容如下:

image

 然后在 TestDll.cpp 文件 添加代码,如下

#include "pch.h"
#include "TestDll.h"
#include<iostream>

void HelloWorld(char* name)
{
    std::cout << "Hello World " << name << std::endl;
}

int Test()
{
    return 666666;
}

int Add(int a, int b)
{
    return a + b;
}

 

C++库导出有两种方式,建议两种方式同时使用

 

1、以C语言接口的方式导出

在函数前面加上 extern "C" __declspec(dllexport)

extern "C" __declspec(dllexport) void HelloWorld(char* name);
extern "C" __declspec(dllexport) int Test();
extern "C" __declspec(dllexport) int Add(int a,int b);

 

或者使用 extern "C" 包装  类文件

#pragma once

#ifdef __cplusplus
extern "C" {
#endif 
    class TestDll
    {
         __declspec(dllexport) void HelloWorld(char* name);
         __declspec(dllexport) int Test();
         __declspec(dllexport) int Add(int a, int b);
    };
#ifdef __cplusplus
}
#endif

 

2、以模块定义文件的方式导出

在源文件上点击右键,选择添加-》新建项,然后选择 代码-》模块定义文件,添加TestDll.def 文件

image

 

在TestDll.def 中输入 代码如下:

LIBRARY "TestDll"

EXPORTS   //下边是要导出的函数 不需要分号隔开

HelloWorld @ 1 
Test @ 2
Add @ 3

 

编译生成dll。这里需要注意的是,如果生成是64位的库,C#程序也要是64位的,否则会报错

image

 

三、C#项目HelloWorldTest下 添加代码

注意 导入命名空间using System.Runtime.InteropServices;

在DllImport导入C/C++编写的动态库时函数,可以加上一些约定参数,例如:

[DllImport(@"HelloDll.dll", EntryPoint = "Test", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]

CallingConvention = CallingConvention.Cdecl,来指定入口点的调用约定

C/C++编写的动态库默认的入口点约定为_cdecl,VS 默认调用动态库时的约定为_winapi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldTest
{
    internal class Program
    {
        [DllImport("HelloDll.dll")]
        public static extern void HelloWorld(string name);
        [DllImport("HelloDll.dll")]
        public static extern int Test();
        [DllImport("HelloDll.dll")]
        public static extern int Add(int a, int b);

        static void Main(string[] args)
        {
            Console.WriteLine(Test().ToString());
            Console.WriteLine(Add(2, 5));
            HelloWorld("大大大大大猩猩");
            Console.ReadKey();
        }
    }
}

 

然后生成程序 ,注意生成格式要一致

image

 

把HelloDll.dll添加 HelloWorldTest 项目的引用中 或 把 HelloDll.dll文件放到HelloWorldTest.exe 所在目录

image

 F5 启动程序 

image

 

posted on 2025-08-27 14:14  大大大大大大猩猩  阅读(637)  评论(1)    收藏  举报