Call a C dll from C#

P

Peter Kirk

Hi

how do I call functions in a DLL written in C from C#.
Eg. in Java it is necessary to use jni - is there something similar in C#?

Thanks,
Peter
 
M

Michael C

Peter Kirk said:
Hi

how do I call functions in a DLL written in C from C#.
Eg. in Java it is necessary to use jni - is there something similar in C#?

Here's an example

using System.Runtime.InteropServices;

[DllImport("kernel32", EntryPoint= "GetComputerNameA")]
private static extern int GetComputerName(String lpBuffer, ref int nSize);
 
M

Michael C

Michael C said:
Peter Kirk said:
Hi

how do I call functions in a DLL written in C from C#.
Eg. in Java it is necessary to use jni - is there something similar in
C#?

Here's an example

using System.Runtime.InteropServices;

[DllImport("kernel32", EntryPoint= "GetComputerNameA")]
private static extern int GetComputerName(String lpBuffer, ref int nSize);

Oops, that wouldn't actually work because you can't pass a string in like
that but substitute a byte array or string builder and it would.
 
L

Leon Lambert

If you are using .Net 2.0 and VS2005 its a lot easier to deal with
interfacing managed code with unmanaged code. It supports pragmas for
switching back and forth.
#pragma managed
#pragma unmanaged

This way you can write an managed C++ interface dll and just include the
..h files from the C code. Inside the the dll you can pretty much write
managed code while using the unmanged classes and methods. It magically
figures out how to do the marshaling for you.
From C# you can just use the dll and call the methods directly since
they are managed and you don't need to use pInvoke. There is also a
speed benefit for doing this because the compiler optimizes the marshaling.

I figured a lot about this by looking into the "#pragma managed" help
documentation and other links that VS2005 provided.

Hope this helps.
Leon Lambert
 

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

Top