Calling a C-function from C# ???

H

Henrik

I have been googling for hours now without being able to find just _one_
example / guide on how to call a C-function from C# Not a C++
function,...but a C-function!!

I have tried to create a solution in VS 2010 and add two projects to that
solution.

One project is a C-project that only contains one file myfile.c

The contents of myfile.c looks like this:

int addTwo(int x, int y)
{
return (x + y)
}

The other project is a C# project with a file called program.cs

In that file I have written:

[DllImport("mydll.dll", EntryPoint= "addTwo")]
static extern int addTwo(int x, int y);

static void Main(string[] args)
{
Console.Writeline(addTwo(5,2).ToString());
}


I get a System.EntryPointNotFoundException.

Unable to find entry point named 'addTwo' in DLL 'mydll.dll'

What am I doing wrong here???
 
H

Henrik

I got it to work thanks to you :blush:)

But now I get a PInvokeStackImbalance.

I updated the zip file so you could take a look at it
 
H

Henrik

But now I get a PInvokeStackImbalance.


Fixed it...types didn't match..

Any good links to a table which maps types between C and C# ?
 
H

Henrik

But now I get a PInvokeStackImbalance.


Fixed it...types didn't match..

Any good links to a table which maps types between C and C# ?
 
H

Henrik

??? What types didn't match?

The C function argument types did not match the types of the static extern
function
defined in the C# file.

Sorry if my lingo is a bit off. I hope you understand what I mean?

Is there a table somewhere where I can see what ANSI C types like int,
short, long etc. maps to
in c# ?
 
H

Henrik

But, the C# type sizes are well-defined and documented. So you can
easily correlate that information with whatever you know about your
specific C DLL.

Ok so if I know that one of the arguments in a C-function is 16bit signed
then I just look up in a C# ref manual what a 16bit signed int is called ?
 

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