Search code examples
c#php.netcom

How to return an array from a c# dll to php


I have the following c# class library:

using System.Runtime.InteropServices;

namespace phptest
{
    public class Class1
    {
        public int getint()
        {
            return 17;
        }

        public string getstring()
        {
            return "yup";
        }

        public int doubleint(int x)
        {
            return x * 2;
        }

        public string doublestring(string s)
        {
            return s + s;
        }

        [return: MarshalAs(UnmanagedType.SafeArray)]
        public int[] getintarray()
        {
            return new int[] { 1, 7, 9 };
        }
    }
}

and the following php script to test it:

$obj = new COM("phptest.Class1");
print $obj->getint();
print "\r\n" . $obj->getstring();
print "\r\n" . $obj->doublestring("dog") . "\r\n";
print $obj->doubleint(11);
$x = $obj->getintarray();
print_r($x);

It all works except for the getintarray();

The last line of the php script outputs: variant Object

var_dump($x) comes up with blank.

if I change the c# to return an array of objects instead:

[return: MarshalAs(UnmanagedType.SafeArray)]
public object[] getintarray()
{
    return new object[] { 1, 7, 9 };
}

then var_dump($x) comes up with:

object(variant)#2 (0) {
}

How do I get at the values in the array passed back by the c# dll?

Is there something I need to do to the c# or the php or both?

I'll also be needing string arrays, so any help on that would be most welcome too.

EDIT:

As suggested by Michael, I tried the following:

[return: MarshalAs(UnmanagedType.LPArray)]
public int[] getintarray()
...

It has the same returns as when I had it returning an object array.

Also count($x) gives me the number of elements in the returned array (3 in this case)

I have tried accessing the elements in the following ways:

$x[0]          outputs "variant Object"
$x->value      outputs nothing
$x[0]->value   outputs nothing
$x->0          outputs nothing

var_dump($x[0]) gives me the same as var_dump($x)


Solution

  • Not the best way to do it but see if you are able to get anything with this in Php.

    foreach($x as $array){
        echo "Value ".$array. "<br/>";
    }