windows下用C#调用C++代码的一个方法
首先用Visual Studio创建C++ 动态链接库项目 :【C++ 动态链接库(DLL) 生成可在多个正在运行的Windows应用之间共享的.dll】
然后C#代码调用这个dll文件
具体步骤
1.创建c++项目

// MathLib.cpp
#include "pch.h"  
#include <string>
#include <windows.h>
// 导出函数声明(C风格命名,避免C++名称修饰)
extern "C" __declspec(dllexport) int Add(int a, int b);
extern "C" __declspec(dllexport) const char* GetGreeting(const char* name);
// 加法函数实现
int Add(int a, int b) {
    return a + b;
}
// 字符串拼接函数实现
const char* GetGreeting(const char* name) {
    // 注意:为了简化示例,使用静态缓冲区(实际项目需考虑线程安全)
    static char buffer[256];
    sprintf_s(buffer, "Hello, %s! This message comes from C++ DLL.", name);
    return buffer;
}编译为dll文件
2.
using System;
using System.Runtime.InteropServices;
class Program
{
    // 注意:路径中的反斜杠需要用双反斜杠,或在字符串前加@
    [DllImport(@"E:\.revit开发代码库(c#)\开源项目\Revit2GLTF-main\x64\Debug\Dll1.dll",
               CallingConvention = CallingConvention.Cdecl)]
    public static extern int Add(int a, int b);  // 替换为你的函数名
    [DllImport(@"E:\.revit开发代码库(c#)\开源项目\Revit2GLTF-main\x64\Debug\Dll1.dll",
               CallingConvention = CallingConvention.Cdecl,
               CharSet = CharSet.Ansi)]
    public static extern IntPtr GetGreeting(string name);  // 替换为你的函数名
    static void Main()
    {
        try
        {
            // 调用加法函数
            int result = Add(10, 20);
            Console.WriteLine($"C++ Add(10, 20) = {result}");
            // 调用字符串函数(注意:C++返回的字符串需用Marshal转换)
            IntPtr greetingPtr = GetGreeting("CSharp");
            string greeting = Marshal.PtrToStringAnsi(greetingPtr);
            Console.WriteLine(greeting);
            Console.ReadKey();
        }
        catch (DllNotFoundException)
        {
            Console.WriteLine("找不到MathLib.dll,请确认DLL路径正确");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"调用出错:{ex.Message}");
        }
    }
}可以创建一个c# console 进行调用
注意: c#代码里面要有上面的导入的C++编译的dll文件的正确路径
运行console即可输出结果

posted on 2025-10-30 15:23 sswsswssw1996 阅读(0) 评论(0) 收藏 举报
 
                    
                 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号