How to create C# DLL to use in PHP

I’m using a C#.NET DLL with ASP.NET 2.0 and it’s working now. I want to use the same DLL in PHP.

I’m a newbie in PHP; would someone please tell me how to use it in PHP or could you share some example?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

PHP has a built-in Windows-only extension called DOTNET that allows you to use .NET libraries in a PHP application.

Note that you’ll need to make sure your assemblies are declared as COM visible:

[assembly: ComVisible(true)]

Here are two examples.

<?php
 $stack = new DOTNET("mscorlib", "System.Collections.Stack");
 $stack->Push(".Net");
 $stack->Push("Hello ");
 echo $stack->Pop() . $stack->Pop();
?>

Another example demonstrating functionality of DOTNET class:

<?php

$full_assembly_string = 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a8425bc35256e463';
$full_class_name = 'System.Windows.Forms.Form';
$form = new DOTNET($full_assembly_string, $full_class_name);

// code to add buttons, menus, text, etc

$form->Show();

$form_event = '';
while($form_event !== 'close') {

  // handle form functions and events

  }
?>

Method 2

you are using the PHP Version 5.4.7 you should already have com_dotnet.dll
if you dont have it you can download it on “download” and add to your ext/ path inside php directory.

Edit you php.ini file

extension=php_com_dotnet.dll

Method 3

What you really need is this:

  • Enable COM-Visibility (I was wrong before)
  • Sign your assembly (give it a “stong name”, use “sn.exe” to create public-private-keys)
  • Add your assembly to GAC (use “gacutil.exe”)
  • When you change your assembly, before adding it to GAC again, make sure your AssemblyVersion (not FileVersion) changes/goes up (you can go down as well)

(you find those tools most probably in “C:Program Files (x86)Microsoft SDKsWindows …”, just google for their correct use, easy enough)


That should do it.
In PHP (example):

<?php
    // use this kind of name, not path to dll or whatever
    // print your assemblly's full name in .NET and use that
    $name = "YourAssembly, Version=1.1.1.1, Culture=neutral, PublicKeyToken=fe6263478ac";
    $obj = new DOTNET($name, "YourNamespace.YourClass");
    echo "successn";
?>

Oh yeah, vaibhav is right about “php.ini”. I didn’t have to edit it. It had the correct values (defaults maybe?).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x