Calling C functions from C#

Posted on 2004-11-24
Last Modified: 2010-05-18
Well, as you can see I'm a first timer...
how do i call a C function from a C# class?
can it be done in the same project or do I need to reside the C code in a Lib?
a simple example will be appreciated.
Question by:udibs
    LVL 8

    Accepted Solution

    You will need to use DLLImport, for example:

    [DllImport("MyDLL")] // or the complete dll path
    public static extern string MyMethod(int x);

    and then you can simply use that function in your code:

    string s = MyMethod(55);


    LVL 48

    Expert Comment


    Author Comment

    Must I use a DLL or can I use a static lib?
    LVL 48

    Assisted Solution

    C# doesn't work with static libraries. PInvoke requires Dll.
    LVL 8

    Expert Comment

    right now you'll have to either use a dll or add a c and a c# project to your solution and reference one from the other (which results in a dynamically loaded dll behind the scenes).

    In vs2k5 you'll have the ability to mix code files from different languages in a single project

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
    This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    758 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now