切片DLL句柄类

时间:2012-03-16 20:33:12

标签: c++ dll

我有一个Visual Studio 2008 C ++项目,我正在创建一个带有C接口的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;
}

1 个答案:

答案 0 :(得分:1)

不优雅,但它会起作用:

  • 您的UserDataUserDataEx结构与指针类型不同。将这两个结构合并为一个,并用FARPROC替换回调指针类型。在设置和检索这些函数指针时,您必须来回转换。
  • 您还需要在结构中添加某种显式类型信息,以指定是否将回调转换为标准版本或&#34; Ex&#34;版。例如,您可以添加flags字段并设置USES_EXTENDED_CALLBACK标记。