dll中的函数具有以下原型
void Foo(int arg1, int& arg2);
Run Code Online (Sandbox Code Playgroud)
问题是,如何在C中声明函数原型?
声明合法吗?
void Foo(int, int*);
Run Code Online (Sandbox Code Playgroud)
声明合法吗?
它是,但它没有声明相同的功能.如果您需要C API,则无法使用引用.坚持指针,并确保该函数具有C链接:
extern "C" void Foo(int, int*) {
// Function body
}
Run Code Online (Sandbox Code Playgroud)
如果您无法修改DLL代码,则需要为其编写一个C++包装器,以便公开适当的C API.
小智 5
你需要一个适配器,它包含一个C++转换单元和一个可以从C和C++使用的头,就像这样(当然使用更好的名称):
adapter.h:
#ifndef ADAPTER_H
#define ADAPTER_H
#endif
#ifdef __cplusplus
extern "C" {
#endif
void adapter_Foo(int arg1, int *arg2);
// more wrapped functions
#ifdef __cplusplus
}
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
adapter.cpp:
#include "adapter.h"
// includes for your C++ library here
void adapter_Foo(int arg1, int *arg2)
{
// call your C++ function, e.g.
Foo(arg1, *arg2);
}
Run Code Online (Sandbox Code Playgroud)
您可以将此适配器编译为单独的DLL,也可以将其作为主程序的一部分.在您的C代码中,只需#include "adapter.h"调用adapter_Foo()而不是Foo().
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |