我想在 c++
中创建一个多线程记录器,它也可以从 c
代码中调用。
这是在我的 source.cpp
文件中:
#include <cstdlib>
#include <iostream>
#include <thread>
#include "source.h"
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
class thread_obj {
public:
void operator()(float* x)
{
printf("value: %d", x);
}
};
void log(float value)
{
thread th1(thread_obj(), value);
th1.join();
}
#ifdef __cplusplus
}
#endif
这是在 source.h
中:
#ifdef __cplusplus
extern "C" {
#endif
void log(float value);
#ifdef __cplusplus
}
#endif
现在我想在 C
文件中使用它,例如:log(myFloatValue);
,当然还有包含的头文件。
但是我遇到了一些奇怪的错误,比如:
Error C2672 'invoke': no matching overloaded function found myproj C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread 43
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Ty1 &&,_Types2 &&...) noexcept(<expr>)' myproj C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread 39
Error C2780 'unknown-type std::invoke(_Callable &&) noexcept(<expr>)': expects 1 arguments - 2 provided hackatlon_0_0_1 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread 39
我的问题是,我该怎么做,或者我该如何解决这些错误?
最佳答案
您的代码存在多个问题:
- operator() 的参数应该是
float x
而不是float*
因为这是你传递给线程的内容 - 您的日志函数与标准数学日志冲突。更改函数名称或将其放入不同的命名空间
- printf 使用格式说明符
"%d"
。它应该是"%f"
因为输入是 float - 您不需要为类放置
extern "C"
。您正在避免仅对需要从 c 文件调用的log
函数进行名称修改。
关于c++ - 如何在 C++ 中创建多线程记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69589101/