Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c调用c++dll

作者:叶枫殇   发布日期:2025-03-12   浏览:321

// C 代码调用 C++ DLL 示例

// 假设我们有一个名为 mycppdll.dll 的 C++ 动态链接库,其中包含一个导出函数 add。

// 首先,我们需要在 C++ 中创建一个 DLL,并确保函数以 C 链接方式导出。
// 在 C++ 中,我们可以使用 extern "C" 来确保函数名不会被修饰(mangled),从而可以被 C 代码正确调用。

// C++ DLL (mycppdll.cpp)
/*
extern "C" __declspec(dllexport) int add(int a, int b) {
    return a + b;
}
*/

// 接下来是 C 代码中如何调用这个 C++ DLL。

#include <stdio.h>
#include <windows.h>

typedef int (*AddFunc)(int, int);

int main() {
    // 加载 DLL
    HMODULE hDLL = LoadLibrary("mycppdll.dll");
    if (hDLL == NULL) {
        printf("Failed to load DLL\n");
        return 1;
    }

    // 获取函数指针
    AddFunc add = (AddFunc)GetProcAddress(hDLL, "add");
    if (add == NULL) {
        printf("Failed to get function address\n");
        FreeLibrary(hDLL);
        return 1;
    }

    // 调用函数
    int result = add(3, 4);
    printf("Result: %d\n", result);

    // 卸载 DLL
    FreeLibrary(hDLL);

    return 0;
}

解释说明:

  1. C++ DLL:

    • 使用 extern "C" 确保函数名不会被 C++ 编译器修饰,以便 C 代码能够正确找到函数。
    • 使用 __declspec(dllexport) 导出函数,使其可以在外部访问。
  2. C 代码:

    • 使用 LoadLibrary 加载 DLL。
    • 使用 GetProcAddress 获取导出函数的地址。
    • 使用 FreeLibrary 卸载 DLL。
    • 通过函数指针调用导出函数。

上一篇:c++if语句

下一篇:菜鸟c++

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站