Click to See Complete Forum and Search --> : Global instances not calling constructor


Twigg
November 16th, 2005, 02:40 PM
I'm wrapping a C++ library into a managed C++ dll.

What I'm finding is that non of the constructors for my global\static classes or structures are getting called. The constructors get called fine when I create the items locally or new them off the heap, but in the example below the contructor never gets called.

struct testclass
{

int i;

testclass()
{
i=1;
}


};

testclass MyTestClass;

void SomeFuntion()
{
MyTestClass.i += 1; //i == 1 (not 2)

testclass MyTestClass2;

MyTestClass2.i += 1; //i == 2 (perfect)

}


Does anyone now why the constructors aren't getting called for Global\Static vars?

Boris K K
November 17th, 2005, 04:07 AM
By "wrapping" do you mean:

Changing your DLL to mixed native/managed code
or
Creating a new DLL, which provides managed API and uses the "old" DLL?


Also, do you have problems with the initialization of managed or unmanaged classes?

cilu
November 17th, 2005, 06:37 AM
Does this DLL have an entry point (DllMain) or not?

Bornish
February 15th, 2006, 08:43 AM
A DLL without an entry point has no way to initialize static variables except for very simple types such as integers. You should not normally have any static variables in a /NOENTRY DLL.Right-click on your project name to change its properties. On the property page select All Configurations. In Configuration Properties treeview expand Linker and choose Command Line option. At Additional Options there should be /noentry option which needs to be removed.

Please see attached solution containing 3 projects:
- TestForm - a simple form loading following user controls
- NoStatics - a user control linked with /noentry (default setting)
- InitStatics - a user control linked without /noentry

These sample controls are having the same implementation, but NoStatics fails to call any constructors for static objects.

To load & try the solution, double-click on "StaticsInManagedDlls\InitStatics\InitStatics.sln" and press F5 to run (you'll have to confirm a full rebuild).

Regards,