<p>I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration:</p>

<pre><code>__declspec(thread) int lastId = 0;
</code></pre>

<p>However, at the first access of the variable, I get a NullReferenceException.
To be more precise, the declaration is done within a <em>ref class</em> (a .NET class implemented in C++/CLI).</p>

<p>I have already read something about __declspec(thread) does not work with delay loaded DLLs.
Am I using delay loaded DLLs automatically if I use .NET?</p>

It seems that __declspec(thread)
isn't supported by CLR
.
Take in mind that .net threads aren't necesarily native threads,
but can be also fibers
, so standard API's for threads don't work on them.
If you have a managed class, then you should use managed threading API's for
thread local storage
.
There are a lot of articles regarding this difference. This is just to get you started.
As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve
performance
. In case you are working with ASP.NET applications, you need to remember
some things
about TLS.