C # calls the C (c + +) DLL sample tutorial, which contains a workaround for a DLL that cannot find a function entry, including the C#dll method of calling the solution to the error __jquery

Source: Internet
Author: User

This article is about how to invoke C (c + +)-written DLLs in a C # environment.

"Reprint marked the source."

First, the preferred creation of a C DLL project, production DLL files used for standby, steps are as follows:

1, VS2010 create C + + Project Select Win32 Application, the name is Createcdll, in the application settings interface to select the DLL, the following figure:

2, in the above figure in the Attachment option to select "Export symbol" click Complete, then generated C + + DLL project, the following figure

You can see that the benefit of choosing the export symbol is that the project automatically helped us create the CREATECDLL_API macros, which is what we're going to export to the DLL using the keyword to see CREATECDLL_API's original definition as F12:

The following ifdef blocks are a standard way to create a simpler//macro that exports from a DLL
. All files in this DLL are compiled with the createcdll_exports//symbol defined on the command line
.
This symbol should not be defined on//any other project that uses this DLL. In this way, any other project that contains this file in the source file treats the
//Createcdll_api function as if it were imported from a DLL, and this DLL treats the//symbol defined by this macro
as being exported.
#ifdef createcdll_exports
#define CREATECDLL_API __declspec (dllexport)
#else
#define Createcdll_ API __declspec (dllimport)
#endif

There are three files in the source file in the diagram above, The first CreateCDll.cpp is what we're going to write. dll interface function source file (engineering automatically helped us create three examples a variable a function a class, in order to be simple we can delete these three pieces of code), dllmain.cpp similar to the DLL's main entrance, Stdafx.cpp will not be introduced, okay, so we start adding our interface functions in CreaeCDll.cpp, in order to test our simple write two functions, one is to find two number and function, the second is to compare the size of two numbers, and output the maximum, good to this source code as follows:

CreateCDll.cpp: Defines the exported function of a DLL application.
//

#include "stdafx.h"
#include "CreateCDll.h"

//sum
CREATECDLL_API int fnadd (int num1,int num2)
{return
	num1 + num2;
}
Find the maximum
createcdll_api int fnmax (int num1,int num2)
{return
	(Num1 > num2)? num1:num2;

3, OK to this we have two interfaces have been written, we compile the project, you can see the project in the Debug directory has produced a DLL and Lib file, the following figure:

4. Okay, step three. We have already produced the DLL, below we want to create C # project to call just generated DLL, we create a C # window application name is Importcdll, save, add the following interface:

5. Copy the DLL file just generated to the debug directory of C # project, and then complete the following code in C #:

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;

Using System.Runtime.InteropServices; namespace Importcdll {public partial class Form1:form {//Import the function interface in the sum DLL [DllImport ("Createcdll.
        DLL ", entrypoint=" Fnadd ")] private static extern int Fnadd (int num1, int num2); Import a function interface in the maximum DLL [DllImport ("CreateCDll.dll", EntryPoint = "Fnmax")] private static extern int Fnmax (int

        NUM1, int num2);
        Public Form1 () {InitializeComponent (); private void Form1_Load (object sender, EventArgs e) {}//Sum button event private Voi D Button1_Click (object sender, EventArgs e) {textbox3.text = string.
        Format ("{0}", Fnadd (Convert.ToInt32 (TextBox1.Text), Convert.ToInt32 (TextBox2.Text)); }//Max button Event private Void button2_click (object sender, EventArgs e) {textbox4.text = string.
        Format ("{0}", Fnmax (Convert.ToInt32 (TextBox1.Text), Convert.ToInt32 (TextBox2.Text));
 }
    }
}
6, the above code has completed the corresponding operation see code comments, you need to be aware of the need to add: using System.Runtime.InteropServices reference to use the DLL, good compile run, when we click the sum or maximum value when we found the error is the following figure:

Hint can't find the function portal ... What's going on? To confirm that there is really no entry for our two functions in the DLL, we use PE Explorer to open our CreateCDll.dll file to see the function entry name inside, and find the following figure:


We can see that our function names have been changed into:? fnadd@ @YAHHH @z (corresponds to Fnadd) and? fnmax@ @YAHHH @z (corresponding Fnmax), what's the matter, the original compiler in the compiler will automatically in our function to add a flag character, So we need to use a DEF file to tell the compiler not to change our interface name when making DLL files. As follows.

7, such as the error required in the C's DLL project to add def file to tell the compiler not to modify our function interface name, on the project right click Add----> New project, select module definition file (. def), the following figure:

Enter Mydef, click Add, add the following code under the Mydef file:

LIBRARY "Createcdll"
exports
fnadd
Fnmax
Add your DLL name after the LIBRARY, and note that you do not need to add a. dll; directly below exports, you do not need quotes to see the code example above.

Okay, so we'll compile the DLL's project, and then take a look at the function name of the compiled DLL with PE Explorer, and find the following:

The name is already correct, OK again copy to our C # project debug directory, compile again, run.

8, run recompile, click the sum or the maximum button again, and the error ... the error screen is as follows:


After Baidu-google, found that in the DLL call to the "callingconvention" of the value of the call to change to "Callingconvention.cdecl", the default seems to be "stdcall" way ; Modified code as follows:

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;

Using System.Runtime.InteropServices; namespace Importcdll {public partial class Form1:form {//Import the function interface in the sum DLL [DllImport ("Createcdll. DLL ", EntryPoint =" Fnadd ", CallingConvention = callingconvention.cdecl)] private static extern int Fnadd (int num1
        , int num2); 
        Import function interface for maximum DLL [DllImport ("CreateCDll.dll", EntryPoint = "Fnmax", CallingConvention = callingconvention.cdecl)]

        private static extern int Fnmax (int num1, int num2);
        Public Form1 () {InitializeComponent (); private void Form1_Load (object sender, EventArgs e) {}//Sum button event private Voi D Button1_Click (object sender, EventArgs e) {textbox3.text = string. Format (' {0} ', Fnadd (convert.toint32 textBox1.text), Convert.ToInt32 (TextBox2.Text));  }//Max button event private void Button2_Click (object sender, EventArgs e) {textbox4.text = String.
        Format ("{0}", Fnmax (Convert.ToInt32 (TextBox1.Text), Convert.ToInt32 (TextBox2.Text));
 }
    }
}

9, compile the operation again, OK the effect is as follows:


OK, this is the end, I hope to help the novice.

Related Article

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.