1

i'm new in C#.

I have a C file like this (and im using it to make DLL file) :

extern "C"
{
    typedef int (__stdcall * t_fun)(int);

    __declspec(dllexport) int __stdcall ExecuteC(int n, t_fun f)
    {
        return f(n);
    } 
}

Then i want to use it in my C# code using PInvoke.

public delegate int f_delegate(int n);

[DllImport("ExecuteC.dll")]
        public static extern int ExecuteC(int n, f_delegate func);

public static int FunCS(int n){ return n; }

static void Main(string[] args)
{
    int x = ExecuteC(13, FunCS);
    System.Console.WriteLine(x.ToString());
}

And when i start my program it ends immediatly. What is the problem here?

1
  • You need to get some diagnostics. Ends immediately is no good. Commented Apr 14, 2014 at 12:15

2 Answers 2

2

I haven't tried running your program, but are you sure you don't just need a

System.Console.ReadLine()

call at the end to stop the console window disappearing immediately?

Sign up to request clarification or add additional context in comments.

2 Comments

No, my program ends when it calls ExecuteC function.
In that case, I recommend you add a try{ ... } catch (Exception ex) { ... } around your Main function in order to get more information on the exception. However, if the error is inside the unmanaged code, you will have to debug that issue separately.
0

The code in the question is fine. You can easily verify this by pasting it into brand new projects and discovering that it works perfectly well.

The only plausible explanations that I can see are:

  1. The program runs correctly and ends very soon after it starts because that is the expected behaviour. After all the program simply prints a single value and terminates.
  2. Your code is in fact different from that presented in the question.

1 Comment

Well, this is weird. Mayby the problem was, that i had 2 projects in different solutions. I created new solution and made 2 projects there and everything works perfectly (with the same code as above). Thx for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.