PHP Call DLL Experience Summary

Source: Internet
Author: User

Recently make a website, need to use the remote data frequently, the data interface is already done. When doing the conversion encountered a performance problem: began to use PHP to achieve the conversion, struggled for several days, did not find a way to directly manipulate bytes. Although the pack () method can be used to press each data into the structure, but it cannot be solved simply by unpack () when extracting, it needs to pass

PHP code
for ($i = 0; $i < $length; $i +=2) {
$TEMPSTR = $tempstr. Chr (Hexdec (substr ($array ["Data"], $i, 2));
}
$array ["data"] = $TEMPSTR;

This type of method is decoded. The frequent use of various string operations will undoubtedly have a significant impact on performance. After research, it is found that the following methods can be implemented for byte operation:

    • Use stream for Read and write
    • Read and write using the socket
    • Using COM DLLs to convert data in C + + DLLs

Because the web cannot find the relevant documents (in fact, did not look for it), the stream and socket has been pass off. In order to compile COM DLL, also specifically downloaded VC + + 6.0 (why not install 2005?) The hard drive is too small to fit, no way AH). After the endless Google (all PHP calls VB written DLL information, not much help) and compile/debug, and finally successfully passed the results into PHP.
Here is a brief introduction to the steps and considerations:

  1. In VC + + 6.0, File--New ... Select "ATL COM AppWizard" in projects, fill in the project name, and so on. In this case, the project is named "Atltest".
  2. In the ATL COM appwizard-step 1 on 1 dialog box, "Server Type" selects "Dynamic Link Library (DLL)", followed by finish.
  3. In ClassView, right-click Atltest, select New ATL Object ..., and in the ATL Object Wizard, select the default "simple Object" and then "Next".
  4. In the ATL Object Wizard property, enter the name of the interface in "short name". In this example, the interface name is "test". All the textbox in the Names tab is then automatically populated with the default values. Note Two places: a "Prog ID" (In this case "atltest.test"), and a "Interface" (in this case, "Itest").
  5. After completion, in "ClassView", the "CTest" class is generated under "Atltest classes", and the "Itest" interface is implemented.
  6. Right-click on the "Itest" interface and select "Add Method ...".
  7. In "Add method to Interface", fill in the name and parameters of the method. Note: The return value must be an HRESULT, and the true return value is the last parameter. Like what

    C + + code
    BSTR Encode (unsigned int msgtype, unsigned int msglength, BSTR message)
    This function, to be written

    C + + code
    STDMETHODIMP Ctest::encode (
    unsigned int msgtype,
    unsigned int msglength,
    BSTR message,
    BSTR *result
    )
    Such a form. There is also the return value only accept simple type (do not know why, char** cannot use) and pointers, BSTR can not be used directly.
  8. Complete this function. Of course, for the sake of simplicity, here is a random value assigned to the result, indicating that the parameter was passed successfully. No memory leak issues are considered.

    C + + code
    STDMETHODIMP Ctest::encode (
    unsigned int msgtype,
    unsigned int msglength,
    BSTR message,
    BSTR *result
    )
    {
    BSTR temp =:: SysAllocString (L "asdfasdf");
    *result = temp;

    return S_OK;
    }
  9. Compiled, the resulting ATLtest.dll is registered with Regsvr32 before it can be invoked using COM.
  10. Then write this PHP code://php Code
    $com = new COM ("Atltest.test") or Die ("Cannot build COM component");
    $result = "unhandled string";
    echo ' $result = "'. $result. '"
    ‘;

    $result = $com->encode (1, 1, "11");
    echo ' $result = "'. $result. '"
    ‘;

    $com = null;
  11. Note that the "atltest.test" here is the "Prog ID" in just (4), and the method of using encode () is not the same as the declaration. It does not matter!
    Of course, since there is no three input parameters at all, here's 1, 1, "11" just to satisfy the number of input parameters.
  12. What is the output of this PHP?

    HTML Results
    $result = "Unhandled string"
    $result = "ASDFASDF"
    As can be seen, $result successfully changed to the value assigned in the DLL, indicating that the Encode () method successfully returned the value.

Some questions

    1. Why is the bstr* returned in Encode (), but in PHP, it becomes a string (BSTR)? Is this automatic conversion done by ATL or php?
    2. When does the space allocated by SysAllocString () for a BSTR in C + + code be garbage collected? Where is the responsibility for collecting work? Will it cause a memory leak?
    3. After the evil C + + 6.0 compiler, why does the return value not support char** this simple type (using char** to compile countless errors directly)? A BSTR is essentially a pointer, nor does it support (suggesting that only simple types and pointers are supported), and it has to be written with a nondescript bstr*. Well, the next step is to try using CComBSTR or _bstr_t to try which is better.
    4. For incoming bstr* result, do you need to use SysFreeString () for processing? In C + +, there is no doubt that it needs to be released, but what does PHP do behind the scenes? Is there a garbage collection of non-referenced constant "unhandled strings"?

//////////////////////////////////////////////////////////////////////////

PHP Call DLLProject needs to use PHP call DLL, forum post get ideas, with Dynamicwrapper method call. Download DynamicWrapper.dll to PHP ext with windows system32, $DW = new COM ("Dynamicwrapper"); $DW->register ("EbUsbApi.dll", "Ebcreatedatafile", ' I=sls ', "F=s", "r=l"); $ch = $dw->ebcreatedatafile ("222", 11, "22"); DLL one of the functions HANDLE ebcreatedatafile (LPCTSTR lpfilename, DWORD dwcreationdisposition, LPCTSTR lppassword) Gets the result 0. Success/////// 1. To view CPU load:

CODE:


$WMI = new COM (' winmgmts://');

$processor = $wmi->execquery ("SELECT * from Win32_Processor");

foreach ($processor as $obj) {

$cpu _load_time = $obj->loadpercentage;

}

echo $cpu _load_time;

? >2. To invoke a custom DLL component:
1) Create an ActiveX DLL component--

CODE:

Public Function Hello () as String
Hello = "Hello world!"
End function co-exists as "Test.dll" file

2) Register this component with Regsvr32.exe
regsvr32 test.dll

3) Call this DLL component within PHP:

CODE:

$obj = new COM ("Test.dll");
$output = $obj->hello (); Call the "Hello ()" method
Echo $output; Show Hello world! (So this comes from the dll!)
? >/////////////////////////////////

Today, we are going to make an online payment using the business Silver Interface, which provides two DLL files and a description document, plus an electronic certificate.
PHP calls COM components, from the internet for half a day and did not find a clear, is not with this people too little or too simple

With no one to write.

What is COM?

The COM (Component object model) Component object models are a way to share binary code across applications and languages. Is

The object-pointing layer (the associated service) at the upper part of the DCE RPC defines a common invocation contract to allow code calls in different languages.

and allow other language code to interoperate (the previous question is that the code is COM aware), COM can be loaded as a DLL by the native program can also be

To be called by a remote process through DCOM.

Preparatory work

For example, I made a COM component, a new VB6 project, the ActiveX DLL named Project P_test, the class name is C_test, the file contents of the class are as follows:

Option Explicit
Private Myscriptingcontext as ScriptingContext
Private MyApplication as Application
Private myrequest as Request private myresponse as Response
Private MyServer as Server
Private MySession as Session public

Sub OnStartPage (Passedscriptingcontext as ScriptingContext)
Set Myscriptingcontext = Passedscriptingcontext
Set MyApplication = myscriptingcontext.application
Set myrequest = myscriptingcontext.request
Set Myresponse = Myscriptingcontext.response
Set MyServer = Myscriptingcontext.server
Set mysession = myscriptingcontext.session
End Sub

Public Sub OnEndPage ()
Set Myscriptingcontext = Nothing
Set MyApplication = Nothing
Set myrequest = Nothing
Set Myresponse = Nothing
Set MyServer = Nothing
Set mysession = Nothing
End Sub

Public Function test_number (num) as Variant
If num < 0 Then Get_number_attrib = 1
If num > 0 Then Get_number_attrib = 1
If num = 0 Then Get_number_attrib = 0
End Function

Compile build P_test.dll file

The first step, as a COM component, this DLL to be recognized by the system will first go to the system to report

regsvr32 [path]/[component filename]

regsvr32 c:/windows/system32/p_test.dll
Under System folder system32 not prone to permissions issues

This time the file will not be able to move the location, the system will be used when it comes to this directory to find, if you change the directory must first delete the registration

Re-register again

regsvr32/u [path]/[component filename]

The system will display the window to indicate success, the main idea is that the component Dllregister success or Dllunregister success


The second step is to call it directly.
?
$b =new COM ("P_test.c_test"); The general front is its main file name, followed by its class name. Find this article from the registration table

Pieces can be found

This generates an object called B, and we can use its properties and methods to manipulate the
$a = $b->test_number (-454);
echo $a;
? >
The problem that may be encountered is that when compiling the project, the
Microsoft Active Server Pages Object Library
The reference comes in, the concrete realization "project->references" find the Change library, and tick on.

PHP Call DLL Experience Summary

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.