c++ - 如何将函数指针传递给此函数

标签 c++ function-pointers

我正在尝试使用具有如下定义的线程启动函数的线程库:

int vg_thread_create(VGThreadFunction func, 
  void *arg, 
  VGThreadDescriptor *tid,
  void *stack, 
  size_t stack_size,
  long priority,
  int flags );

VGThreadFunction 是以下类型定义:

typedef void* (*VGThreadFunction) ( void* )

为了论证,我有一个这样的函数:

void doit() {
  cout << "Woohoo printing stuff in new thread\n";
}

此函数的签名不是 void* func(void*) - 我是否被迫使用这样的函数签名?

如果我尝试:

VGThreadFunction testfunc = &doit;

我明白了

错误 C2440:“正在初始化”:无法从“void (__cdecl *)(void)”转换为“VGThreadFunction”

如何使用 vg_thread_create?

编辑

我试过这个:

void* doit(void* donothingvar) {
  cout << "printing stuff in new thread\n";
  return donothingvar;
}

然后在函数中:

VGThreadFunction testfunc = (VGThreadFunction)doit;

int ret = vg_thread_create(testfunc, 0, 0, 0, 0, 0, 0);

然后我在调用 vg_thread_create 时遇到访问冲突。

如果我进入该函数,它实际上会在调用 _beginthreadex 时崩溃

Unhandled exception at 0x0040f5d3 in threadtest.exe: 0xC0000005: Access violation  writing location 0x00000000.

有什么想法吗?

通过进入函数,我发现我必须传递一个有效的指针 - 传递零会导致 null 取消引用。抱歉,有点具体。

最佳答案

是的,函数签名必须匹配。只需在您的函数上放置一个虚拟参数即可。

关于c++ - 如何将函数指针传递给此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12940689/

相关文章:

c++ - 使用坐标矩阵 (OpenCV/C++) 访问图像值

c++ - 结构中的字符数组 - 不更新?

c++ - 无法初始化 512x512 数组

c - 使用 C 中的函数指针重新启动计算机

c++ - 如何从 C++ 中的静态函数内部将指向静态函数的指针作为参数传递给另一个静态函数

c++ - 使用 QVariant::Type 在开关 block 中的用户类型的 GCC 警告

c++ - C++ 中的 FPS 相机可能使用 glm :lookat

C++ 指针成员函数与模板赋值与另一个类的成员函数

c++ - 将 lambda 传递给函数模板

c++ - 将函数指针插入 QMap (Qt)