C++模板化函数调用托管函数
C++ Templated function calling a managed function
我正试图围绕托管类构建一个包装器,以便可以从本机代码中调用它。
以下是托管功能:
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&);
相关文章:
- 构造函数正在调用一个使用当前类类型的函数
- 如何在主函数中调用模板类
- 向量推回调用析构函数时调用析构函数
- 是否可以使用函数指针调用虚拟析构函数?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 没有匹配的成员函数来调用'push_back'错误
- 在模板化类的构造函数中调用构造函数
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如何通过python方法和kwargs来提升python的c++函数和调用
- 推迟析构函数的调用
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- 在模板化的 Rcpp 函数中调用另一个 cpp 函数
- 如何使派生类函数在调用时始终调用相同的基类函数?
- 在成员构造函数之后调用基类构造函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何从不同的类中获取函数来调用在 Main 中声明的对象?
- 为什么我不能像这样在静态成员函数中调用静态成员变量?
- 从带有参数的基函数指针调用基方法
- localtime() 函数正在调用 ___lll_lock_wait_private(),这会使线程陷入死锁
- 我不知道为什么复制构造函数的调用在 c++ 中不稳定