Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI: functions inherited from template class are not visible in C#

I've a hard time figuring out how to make the parent class functions visible in C#.

Assume I've a template class, which defines a function foo()

template <int Dim, typename Type>
public ref class FixedNP
{
public:
  float foo() {return 1;};
};

Then I've a class which inherits from the FixedNP template:

public ref class Vector3fP : public FixedNP<3, float>
{
}

When I try to call the foo() function from the C#, eg.

Vector3fP bar = new Vector3fP();
bar.foo();

it says the function Vector3fP doesn't contain a definition for foo.

When I move the definition of foo() to the Vector3fP class, it works fine. However this is not viable in real code, because the FixedNP template contains quite a lot of functions which should be inherited from approximately 4 different classes.

After some search on the Internet I found that adding the

using FixedNP<3, float>::foo;

to the Vector3fP fixed a similar problem for someone. However in my case it just results in another error, this time when compiling the C++/CLI code:

error C3182: 'Vector3fP' : a member using-declaration or access declaration is illegal within a managed type

Any suggestions how to make my functions visible in C#?

like image 906
stativ Avatar asked Nov 04 '22 09:11

stativ


1 Answers

I think they key is in this claim from Managed Templates on MSDN:

If a template is not instantiated, it’s not emitted in the metadata. If a template is instantiated, only referenced member functions will appear in metadata.

That means that functions that aren't used in the C++ code won't be in the generated DLL and you won't be able to use them from C#. To fix this, you could add a phony function to your C++ code, which references the function:

void phony()
{
    auto vec = gcnew Vector3fP();
    vec->foo();
}
like image 159
svick Avatar answered Nov 12 '22 10:11

svick