C # How to call function pointers delegated to C

Source: Internet
Author: User

The C code is as follows:

# Include "stdio. h"

_ Declspec (dllexport) int Call (int (* qq) (int num), char * str)
{
Printf (str );
Return qqqq (123 );
}
Multiple verifications show that the function pointer passed in C # To C can be run successfully if the delegate does not contain parameters, but the delegate parameter can be either int, string, or other parameters, "Try to read or write the protected memory. This usually indicates that other memory is corrupted. After finding a solution for one day, you can add [UnmanagedFunctionPointer (CallingConvention. Cdecl)] to the delegate Statement of C #. The correct call is as follows:

[UnmanagedFunctionPointer (CallingConvention. Cdecl)]
Public delegate int MyDeg (int num );
Class Program
{
Static void Main (string [] args)
{

Try
{
MyDeg myd = new MyDeg (FF );
Console. WriteLine (Call (myd, "helloworld "));
}
Catch (Exception ex)
{
Console. WriteLine (ex. Message );
}

}

Static int FF (int num)
{
Console. WriteLine (num );
Return num + 1;

}

[DllImport ("my. dll", EntryPoint = "Call")]
Public extern static int Call (MyDeg mm, string str );
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.