C++模板化函数调用托管函数

C++ Templated function calling a managed function

本文关键字:函数 函数调用 C++      更新时间:2023-10-16

我正试图围绕托管类构建一个包装器,以便可以从本机代码中调用它。

以下是托管功能:

void MyManagedFunction(MyStruct iStruct)
{
// Code according to what are the types of the 2 MyStruct members
}
struct MyStruct
{
public MyStruct(Object iValue1, Object iValue2) : this()
{
Value1 = iValue1; // Often contains DateTime::Now
Value2 = iValue2;
}
public Object Value1;
public Object Value2;
}

在我的情况下,Value1几乎总是System::DateTime::Now,Value2几乎总是一种常见的数据类型(int、double、float、string、bool)。我想在包装器中制作两个模板化函数。

在包装的.h中,我有以下内容:

#ifdef MYWRAPPER_EXPORTS
#  define MYWRAPPER  __declspec(dllexport)
#else
#  define MYWRAPPER  __declspec(dllimport)
#endif  
class MYWRAPPER MyWrapper
{
public:
MyWrapper();
~MyWrapper();
template <class T> void MyNativeFunction(T iParam1)
{
MyStruct^ wStruct = gcnew MyStruct(System::DateTime::Now, iParam1);
//The class containing the managed function is a singleton
MyManagedClass::Instance->MyManagedFunction(wStruct); 
}
template <class T, class W> void MyNativeFunction(T iParam1, W iParam2)
{
MyStruct^ wStruct = gcnew MyStruct(iParam1, iParam2);
//The class containing the managed function is a singleton
MyManagedClass::Instance->MyManagedFunction(wStruct);
}
};

这个包装器编译没有问题。当我在纯本机代码中包含.h时,问题显然发生了。由于我不能隐藏模板化函数的内容,所以我管理了在本机端可见的东西,这些东西阻止了本机代码的编译。

我想知道是否有一个变通办法来实现这一点。我不介意我是否被限制为只使用基元类型作为函数的参数。最好的办法是,如果我能够简单地将模板化函数的内容隐藏在本机代码中,这样它就只知道签名

以下是我迄今为止尝试/考虑的内容:

  • 将参数转换为void*并调用一个函数,在该函数中调用托管函数。通过这样做,我无法将void*强制转换回对象,因为我丢失了它的类型,并且使用typeid获取"t"或"W"类型没有帮助,因为不同的编译器会有所不同
  • 为我想要使用的每种类型重载函数。如果我找不到更好的解决方案,我很可能会使用这一方法。问题是它意味着大量过载(尤其是对于考虑组合数量的2参数函数)

如果您知道模板将采用的所有类型,您可以使用这些变量强制实例化它,从而将模板函数的代码放在源文件中,而不是放在头中。

您可以查看在.CPP文件中存储C++模板函数定义中提供的示例

正如他所说,你可以做如下(复制粘贴警报):

.h文件

class foo
{
public:
template <typename T>
void do(const T& t);
};

.cpp文件

template <typename T>
void foo::do(const T& t)
{
// Do something with t
}
template void foo::do<int>(const int&);
template void foo::do<std::string>(const std::string&);