c++ 使用Dll将函数赋给传递给它的结构的指针成员函数

x9ybnkn6  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(165)

我的解决方案(Visual Studio)中有两个项目
我想分配函数

void _OnCycle()
{
    printf("Success\n");
}

指向PluginCallbacks结构的指针成员函数OnCycle

extern "C" unsigned int PluginInit(PluginFuncs * pluginFuncs, PluginCallbacks * pluginCalls, PluginInfo * pluginInfo) {
    pluginCalls->OnCycle = _OnCycle;
    return 1;
}

但是程序崩溃了。下面是完整的代码。
一个二个一个一个
和第二项目

//Project: Dll1
//file: Dll1/Dll1/main.cpp
#include "plugin.h"
#include "main.h"
#include "stdio.h"

void _OnCycle() { 
    printf("Success\n");
}
extern "C" unsigned int PluginInit(PluginFuncs * pluginFuncs, PluginCallbacks * pluginCalls, PluginInfo * pluginInfo) {
    printf("PluginInit called\n");
    pluginCalls->OnCycle = _OnCycle;
    return 1;
}
//Project: Dll1
//file: Dll1/Dll1/main.h
#define EXPORT __declspec(dllexport)
#include "plugin.h"

#ifdef __cplusplus
extern "C" {
#endif
    EXPORT  unsigned int            PluginInit(PluginFuncs* pluginFuncs, PluginCallbacks* pluginCalls, PluginInfo* pluginInfo);
#ifdef __cplusplus
}
#endif
//Project: Dll1
//file: Dll1/Dll1/plugin.h
#pragma once
#include <stdint.h>

typedef struct _Settings {
    uint32_t structSize;
    uint32_t flags;
} Settings;

typedef struct _PluginInfo {
    uint32_t structSize;
    char name[32];
} PluginInfo;

typedef struct _PluginFuncs {
    uint32_t structSize;
    uint32_t(*GetVersion) (void);
}PluginFuncs;

typedef struct {
    uint32_t structSize;
    void (*OnCycle) ();
}PluginCallbacks;

它可以构建,但在执行时崩溃。

//Output
C:\Users\[hidden]\source\repos\Dll1\Release>ConsoleAPplication1
Loading first dll
PluginInit called
PluginInit(a,b,c) returned 1
Now going to call OnCycle

C:\Users\[hidden]\source\repos\Dll1\Release>

看,它崩溃了,因为"完成"消息没有打印。
这是如何正确地完成。

xqkwcwgp

xqkwcwgp1#

看起来我的问题通过创建一个指针,malloc 'ing并将其传递给dll来解决。

PluginFuncs* a = NULL;
    PluginCallbacks* b = NULL;
    PluginInfo* c = NULL;
    a = (PluginFuncs*)malloc(sizeof(PluginFuncs));
    b = (PluginCallbacks*)malloc(sizeof(PluginCallbacks));
    c= (PluginInfo*)malloc(sizeof(PluginInfo));
    std::cout << "PluginInit(a,b,c) returned " << funci(a,b, c) << "\n";
    std::cout << "Now going to call OnCycle\n";
    if (b && b->OnCycle)
        b->OnCycle();
    std::cout << "Done";

并输出

Loading first dll
PluginInit(a,b,c) returned 1
Now going to call OnCycle
Success
Done

谢啦,谢啦

相关问题