gpt4 book ai didi

c++ - 切片 DLL 句柄类

转载 作者:可可西里 更新时间:2023-11-01 18:39:45 25 4
gpt4 key购买 nike

我有一个 Visual Studio 2008 C++ 项目,我正在其中创建一个带有 C 接口(interface)的 DLL。我定义了两种类型的回调函数:常规函数和提供额外数据的扩展函数。

struct Foo {
char a[ MAX_A ];
char b[ MAX_B ];
char c[ MAX_C ];
};
struct FooEx {
char a[ MAX_A ];
char b[ MAX_B ];
char c[ MAX_C ];
char d[ MAX_D ];
};
typedef void ( CALLBACK *USERCALLBACK )( const Foo&, DWORD );
typedef void ( CALLBACK *USERCALLBACK_EX )( const FooEx&, DWORD );

我使用 UserData 结构维护状态。因为我有两种类型的回调,所以我最终得到了两种结构:

struct UserData {
DWORD user;
int zoo;
std::string bar;
USERCALLBACK callback;
};

struct UserDataEx {
DWORD user;
int zoo;
std::string bar;
USERCALLBACK_EX callback;
};

如何在不为每个函数创建单独的 EX 版本的情况下协调我的 API 与两个不同的 UserData 结构?有没有办法模板化回调?或者创建用户数据的基类?

DECLARE_HANDLE( HMYAPI );

// this function is agnostic of the callback type
MY_API HMYAPI MyAPI_Create()
{
return (HMYAPI)new UserData();
}

// This function does not directly use the callback type, but may need to know it to properly deallocate the UserData structure.
MY_API void MyAPI_Close( HMYAPI handle )
{
delete reinterpret_cast< UserData* >( handle );
}

// this function needs to know about the different callback types
MY_API void MyAPI_Register( HMYAPI handle, USERCALLBACK cb, DWORD user )
{
UserData* ud = reinterpret_cast< UserData* >( handle );
ud->cb = cb;
ud->user = user
}

// this function needs to know about the different callback types
MY_API void MyAPI_RegisterEX( HMYAPI handle, USERCALLBACK_EX cb, DWORD user )
{
UserData* ud = reinterpret_cast< UserData* >( handle );
ud->cb = cb;
ud->user = user
}

// this function is agnostic of the callback type
MY_API void Foo( HMYAPI handle, int x )
{
UserData* ud = reinterpret_cast< UserData* >( handle );
ud->bar = "Foo";
ud->zoo = x;
}

最佳答案

不优雅,但它会工作:

  • 您的UserDataUserDataEx 结构除了指针类型外是相同的。将这两个结构合并为一个,并将回调指针类型替换为 FARPROC。在设置和检索这些函数指针时,您必须来回转换。
  • 您还需要向结构中添加某种显式类型信息,以指定是将回调转换为标准版本还是“Ex”版本。例如,您可以添加一个 flags 字段并设置一个 USES_EXTENDED_CALLBACK 标志。

关于c++ - 切片 DLL 句柄类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9744143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com