C # Notes for calling other dynamic library development,

Source: Internet
Author: User

C # Notes for calling other dynamic library development,

1. Background

Programming languages can be said to be varied, which leads to a new problem. The problems related to calling when systems developed in different languages are docked.

The following describes the problems I encountered during interface development and the solutions for reference only. The C # development I used is used to connect to other programs.

2. Specific Practices

First, let's talk about several common interconnection methods for system interconnection. A. Import through an unmanaged dynamic library dll file. B. Call it through the COM component provided by the other party. C. Call through webService.

Currently, this type is commonly used. Let's take a look at the specific call implementation and problems.

A. Import through an unmanaged dynamic library dll file

The general declaration method in C # is as follows. Assume that the provided dll is the long init (char * Addr, int Port, char * Servlet) method provided in InterfaceHN. dll)

[DllImport ("InterfaceHN. dll ")] EntryPoint =" init ", CharSet = CharSet. ansi, ExactSpelling = true, SetLastError = true attribute to specify more detailed information. You can try it. Generally, you only need to specify the function entry point, for example, [DllImport ("InterfaceHN. dll ", EntryPoint =" init ")]

Public static extern init ([externalas (UnmanagedType. VBByRefStr)] ref string addr, Int32 port, [externalas (UnmanagedType. VBByRefStr)] ref string servlet );

Public static extern init ([StringBuilder addr, Int32 port, StringBuilder servlet );

In this method, I have encountered problems such as memory protection, no method change, incorrect value returned by calling methods, and so on.

In this section, we should note whether the parameter types are supported by both languages, or both languages. As mentioned above, the long value is returned, however, Int32 is actually returned, causing a memory protection prompt. Another point is that, in this case, you can use StringBuilder in C # General strings. If not, try [exploralas (UnmanagedType. VBByRefStr)] ref string paras. After a problem occurs, first check whether the parameter type is correct. Generally, the other party does not have a problem, but it does not rule out that the dll given by the other party has a problem.

B. Call it through the COM component provided by the other party.

This method is simple because it is an interface standard. You only need to register it for use, and then add reference to introduce it into your program. You can use the instantiated objects.

Specific registration method: In the system running window, enter the address of the regsvr32 + com component, for example, regsvr32 D: Public Assembly \ RM. ReportEngine. dll. to cancel registration, add the/u Switch later.

C. Call through webService.

This kind of call is also very convenient and popular. You only need to provide the service address. However, you cannot access some environments. Such as vpn and private network. In this case, you cannot directly access the service by adding a service, but you can access the service by getting their service description xml file. If not, you can use the reflection method to create a client proxy as follows:

Public class WebServiceHelper
{
# Region InvokeWebService Dynamic web service call

/// <Summary>
/// Call WebService dynamically
/// </Summary>
/// <Param name = "url"> WebService address </param>
/// <Param name = "methodname"> method name (Module name) </param>
/// <Param name = "args"> parameter list </param>
/// <Returns> object </returns>
Public static object InvokeWebService (string url, string methodname, object [] args)
{
Return WebServiceHelper. InvokeWebService (url, null, methodname, args );
}
/// <Summary>
/// Call WebService dynamically
/// </Summary>
/// <Param name = "url"> WebService address </param>
/// <Param name = "classname"> class name </param>
/// <Param name = "methodname"> method name (Module name) </param>
/// <Param name = "args"> parameter list </param>
/// <Returns> object </returns>
Public static object InvokeWebService (string url, string classname, string methodname, object [] args)
{
Try
{

String @ namespace = "EnterpriseServerBase. WebService. DynamicWebCalling ";
If (classname = null) | (classname = ""))
{
Classname = WebServiceHelper. GetWsClassName (url );
}

// Obtain the WSDL
WebClient wc = new WebClient ();
Stream stream = wc. OpenRead (url + "? WSDL ");
ServiceDescription sd = ServiceDescription. Read (stream );
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter ();
Sdi. AddServiceDescription (sd ,"","");
CodeNamespace cn = new CodeNamespace (@ namespace );

// Generate client proxy code
CodeCompileUnit ccu = new CodeCompileUnit ();
Ccu. Namespaces. Add (cn );
Sdi. Import (cn, ccu );
CSharpCodeProvider csc = new CSharpCodeProvider ();
ICodeCompiler icc = csc. CreateCompiler ();

// Set compilation Parameters
CompilerParameters cplist = new CompilerParameters ();
Cplist. GenerateExecutable = false;
Cplist. GenerateInMemory = true;
Cplist. ReferencedAssemblies. Add ("System. dll ");
Cplist. ReferencedAssemblies. Add ("System. XML. dll ");
Cplist. ReferencedAssemblies. Add ("System. Web. Services. dll ");
Cplist. ReferencedAssemblies. Add ("System. Data. dll ");

// Compile the proxy class
CompilerResults cr = icc. CompileAssemblyFromDom (cplist, ccu );
If (true = cr. Errors. HasErrors)
{
System. Text. StringBuilder sb = new System. Text. StringBuilder ();
Foreach (System. CodeDom. Compiler. CompilerError ce in cr. Errors)
{
Sb. Append (ce. ToString ());
Sb. Append (System. Environment. NewLine );
}
Throw new Exception (sb. ToString ());
}

// Generate a proxy instance and call the Method
System. Reflection. Assembly assembly = cr. CompiledAssembly;
Type t = assembly. GetType (@ namespace + "." + classname, true, true );
Object obj = Activator. CreateInstance (t );
System. Reflection. MethodInfo mi = t. GetMethod (methodname );
If (args = null)
Return mi. Invoke (obj, null );
Else
Return mi. Invoke (obj, args );
}
Catch (Exception ex)
{
Throw new Exception (ex. InnerException. Message, new Exception (ex. InnerException. StackTrace ));
}
}

Private static string GetWsClassName (string wsUrl)
{
String [] parts = wsUrl. Split ('/');
String [] pps = parts [parts. Length-1]. Split ('.');

Return pps [0];
}
# Endregion
}

Call the webservice of the other party using the WebServiceHelper method InvokeWebService (string url, string methodname, object [] args.

Generally, memory problems often occur when calling other systems. The method cannot be found and the connection fails. The returned value is not the expected value. You only need to carefully analyze these problems.

There is nothing that is too difficult to solve. Hope to help you.


C language ^ how to use

A1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010

B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011

^ XOR operator. The bitwise value is 0 and the difference is 1. See the example above.

//
Examples of simple and practical problems:
====================================
======= A ======= B =========
There are two circuits on the top. The two switches are a and B respectively. The opening status is \ [1], and the closing status is/[0].
If both circuits are enabled or disabled.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, the circuit fails in the and B states simultaneously [0]. When a and B are different, the power is charged [1].

C language ^ how to use

A1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010

B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011

^ XOR operator. The bitwise value is 0 and the difference is 1. See the example above.

//
Examples of simple and practical problems:
====================================
======= A ======= B =========
There are two circuits on the top. The two switches are a and B respectively. The opening status is \ [1], and the closing status is/[0].
If both circuits are enabled or disabled.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, the circuit fails in the and B states simultaneously [0]. When a and B are different, the power is charged [1].

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.