On 2004-01-22, Mark Urish <an*******@discussions.microsoft.com> wrote:
Is there a way to import data from an unmanaged dll? For example,
unmanaged.dll:
__declspec(dllexport) int unmanagedErrno;
managed.cs:
class Managed
{
//this doesn't work:
[DllImport("unmanaged.dll")]
static extern int unmanagedErrno;
}
This fails because "extern" doesn't work for data, only methods. Is there a way to access "unmanagedErrno" in managed code?
To be honest, I haven't tried it in Windows - but I do this on Linux
with mono using the dlopen/dlsym/dlclose system calls...
On windows, you could probably call LoadLibrary and then
GetProcAddress... Something like:
class Managed
{
[DllImport("kernel32", CharSet=CharSet.Auto, SetLastError=true)]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", CharSet=CharSet.Auto, SetLastError=true)]
private static extern IntPtr GetProcAddress(IntPtr hModule,
string lpProcName);
public static void Main()
{
int errNo = 0;
IntPtr address = IntPtr.Zero;
IntPtr hModule = LoadLibrary("unmanaged.dll");
if (hModule != IntPtr.Zero)
{
address = GetProcAddress(hModule, "unmanagedErrno");
if (address != IntPtr.Zero)
{
errNo = Marshal.ReadInt32(address);
Console.WriteLine(errNo);
}
else
{
Console.WriteLine("GetProcAddress Failed");
}
}
else
{
Console.WriteLine("LoadLibrary Failed");
}
}
}
HTH
--
Tom Shelton [MVP]