setting envrionment variable in C# and access it within native C++



We are having difficulties getting environment variable within native DLL
written in C++ which is loaded by C# .NET assembly, the env var is set by the
..NET assembly.

We have an existing C++ application, and want to access it within C#. So we
wrote Managed C++ wrapper which access the native C++ DLL. The Managed C++
wrapper is compiled as .NET assembly that C# can access.

The native C++ DLL need to have an environment variable set to work
properly. So within the C#, we use:
public static extern int SetEnvironmentVariable( string name , string
value );
to set the env var.

But within the native C++ DLL, it will fail when trying to do "getenv()",
with error:
Object reference not set to an instance of an object.

1. If we make the C# application as console application and set env var in
the console before start the C# application, it works. But we can't make the
C# app a console app.

2. If we execute within the C# application a .bat file which prints out the
env var, it shows that the env var is set.

Looks that the native C++ DLL can't getenv() on the env var set within the
C# app.

Any solutions for this?

Thanks a lot.

Mattias Sjögren

Looks that the native C++ DLL can't getenv() on the env var set within the

Right. The docs for getenv says

"getenv and _putenv use the *copy of* the environment pointed to by
the global variable _environ to access the environment. getenv
operates only on the data structures accessible to the run-time
library and not on the environment "segment" created for the process
by the operating system." [emphasis added]

Any solutions for this?

Instead of calling SetEnvironmentVariable from C#, can't you call
_putenv from the MC++ wrapper? Should work if if uses the same CRT as
the native C++ library.


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question