0
votes

Turns out this error had nothing to do with gcroot - I connected some constructors shoddily and lost the instantiated object on the way.

For the record, all versions of the code below worked after this fix, but adding the simple Wrapper class allows you to use & and * operators on the wrapped object, which gcroot forbids. I am using the version outlined in the third code block below.


I am trying to use some measuring instruments via a .dll, but I am having problems with the implementation. Writing all the code into the main.cpp and using the object like this works fine:

#using "M3D_FP_USB.dll"
int main(){
    M3D_FP_USB ^obj = gcnew M3D_FP_USB;
    obj->Connect();
    ...
}

However, when I put it into a class and wrap it with gcroot, I get an "Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of the object" on execution.

class User{       
    ...
public:
    User();
    gcroot<M3D_FP_USB^> obj;
}

User::User(){
    obj = gcnew M3D_FP_USB;
    obj->Connect();
    ...
}

I suspect that the gcroot or it being called inside the unmanaged class might prevent the instruments from accessing the M3D_FP_USB object. I tried adding a managed Wrapper class, and give a handle to the Wrapper object to the User class. That didn't solve the problem, though.

class User{       
    ...
public:
    gcroot<Wrapper^> wobj;
}

ref class Wrapper{
    ...
public:
    M3D_FP_USB^ iobj;
    ...
}

Wrapper::Wrapper(){
    iobj = gcnew M3D_FP_USB;
    iobj->Connect();
    ...
}

The new code I have looks like this, but I couldn't test it with the instruments yet. I will update when I get the chance.

Wrapper::Wrapper(M3D_FP_USB^ obj){
    iobj = obj;
    iobj->Connect();
    ...
}

int main(){
    M3D_FP_USB ^obj = gcnew M3D_FP_USB;
    Wrapper Ex(obj);
}
1

1 Answers

0
votes

Does the exception also happen if you make the class managed and just declare the handle directly? Like:

ref class User
{
public:
    M3D_FP_USB^ obj;

    ...
};

Though I don't see why it wouldn't work the way you're doing it...