How to call a C language function in Qt?
In Qt, calling C language functions can be done using Qt’s QLibrary class and QLibrary::resolve() function.
Firstly, use the QLibrary class to load a dynamic link library (.dll or .so file) that contains C language functions.
QLibrary library("path/to/library.dll"); // 替换为动态链接库的路径
if (library.load()) {
// 动态链接库加载成功
// 使用QLibrary::resolve()函数获取C语言函数的指针
typedef int (*CFunction)(int); // 替换为C语言函数的函数指针类型
CFunction cFunction = reinterpret_cast<CFunction>(library.resolve("c_function")); // 替换为C语言函数的名称
if (cFunction) {
// C语言函数获取成功
// 调用C语言函数
int result = cFunction(42); // 替换为实际的参数
// 处理C语言函数的返回值
// ...
} else {
// C语言函数获取失败
// ...
}
// 卸载动态链接库
library.unload();
} else {
// 动态链接库加载失败
// ...
}
In the code above, replace “path/to/library.dll” with the actual path of the dynamic linked library file, “CFunction” with the actual function pointer type of the C language function, and “c_function” with the actual name of the C language function.
Please remember to use reinterpret_cast when using the QLibrary::resolve() function to obtain a pointer to a C function, in order to ensure that the types match.