View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Peter S. Peter S. is offline
external usenet poster
 
Posts: 10
Default Using DLL from C#

Hallo Simon,

of course I already tried "an incremental approach" to my desired solution:

c#-Code:

[ExportDllAttribute.ExportDll("Summe")]
public static int Summe(int A, int B, [MarshalAs( UnmanagedType.AnsiBStr)]
ref string os)
{
os = A.ToString() + B.ToString() + " ok";
return A + B;
}

VBA-Code:

Private Declare Function Summe Lib "MyLib.dll" (ByVal A As Long, ByVal B As
Long, ByRef S As String) As Long

Sub test()
Dim S As String
i = Summe(10, 10, S)
MsgBox S
End Sub

Works fine!!!!!!! The string is given back perfectly.

Peter

"Simon Murphy" wrote:

Peter
It might be worth trying something less ambitious than arrays initially.
What about using your dll just to add 2 numbers and return a double?

VBA uses the __stdcall calling convention rather than __cdecl, but that
should get you a bad calling convention error rather than a crash.

C ints are equivalent to VBA Longs, I suspect that same is true for C#
- that could cause a crash. (a,b,c should be long not integer)

I don't know how arrays are laid out in .net but I can imagine it being
different to C and to what VBA expects.

What specific error are you getting? (access violation?)

Cheers
Simon
Excel development website: www.codematic.net


Peter S. wrote:
Hi everybody,

I'm trying to get access to a selfdeveloped DLL. What I did:

I created a new Classobject in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ZufallArray
{
public class ZufallArray
{
[ExportDllAttribute.ExportDll("ZArray",
System.Runtime.InteropServices.CallingConvention.C decl)]
public static int[] ZArray (int beginn, int ende, int anzahl)
{
int[] ZZahl = new int[anzahl];
Random randObj = new Random();
for (int j = 0; j < anzahl; j++)
{
ZZahl[j]= randObj.Next(beginn, ende);
}
return ZZahl;
}
}
}

I exported the function with "ExportDLL"
(http://www.codeproject.com/KB/dotnet/DllExport.aspx) and checked the result
with Dependency Walker.

I used the function with VBA (Excel):


Declare Function Zar Lib _
"C:\........\bin\Release\ZufallArray.dll" _
Alias "ZArray" (ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)
As Integer()

Sub zarray()
Dim a() As Integer
a = Zar(10, 20, 3)
For i = 1 To UBound(a)
MsgBox a(i)
Next i
End Sub

Excel crashes! Why?

P.S.: I don't want to use the function by using a reference to .... .tlb and
than creating a new class in Excel (in this case the function must be defined
without "static). By the way this is working pretty good.

I want to use the function this way, because if this works, I can use the
function in other applications.

Peter