How to use an existing VB dll with C#

  • Thread starter Thread starter Eric B
  • Start date Start date
E

Eric B

Hello,

I'm looking for an example of code which shows how to use an existing
VB dll with C#.

So far, many posts that I have looked through simply talk about
problems dealing with issues like "cannot convert from 'ref string' to
'ref object'". But what I'm looking for is an actual working example.
:)

Lets just say I have a fake dll named A.dll with a function named
Test().

Function Test(ByVal arg1 As Variant, ByRef arg2 As Variant) As Variant
Dim strParam2 as String

On Error GoTo Error
If arg1 = "1" Then
strParam2 = "One"
Else
strParam2 = "Whatever Value"
End If

arg2 = strParam2
Test = 0

Exit Function

Error:
Test = -1
End Function


I know arg1 and arg2 have to be passed in as an object because they
are declared as Variant, but what about the return value of Test.

Note: Both arguments will be eventually converted to string.


What would be the code to get the value of arg2, as well as int for
function Test()?

Just so you know, I have tried to create what seems to be a pretty
simple example of this but was unable to get it working. It compiles
fine, but when the code is executed I keep getting an: "Unable to find
an entry point named Test in DLL A.dll" message.
I'm using the line: [DllImport("A.dll",EntryPoint="Test")].

What does this mean?

I should mention that I do not want to change existing dlls to work
with C# unless absolutely necessary.


Thanks in advance,
Eric B
 
Thanks Madhu for the reply,

Your insight to COM vs win32 dlls set me on the correct path and
allowed me to find the solution.

Here is the solution, just in case other users are having the same
problem.

Using my fake dll example named A.dll with a function named Test(),
within a class named clsA:

Function Test(ByVal arg1 As Variant, ByRef arg2 As Variant) As Variant
Dim strParam2 as String

On Error GoTo Error
If arg1 = "1" Then
strParam2 = "One"
Else
strParam2 = "Whatever Value"
End If

arg2 = strParam2
Test = 0

Exit Function

Error:
Test = -1
End Function


Add a reference to the A.dll from within your C# project.

Type or Paste this code into your project where you are trying to use
the COM object.

//NOTE: When you type A. intellisense will provide an option for clsA
(the original class) and _clsA (the Interop class). Use _clsA.

A._clsA myTest = new A.clsAClass();
object x;
string returnString = "";
object arg1 = "1";
object arg2 = returnString;
decimal val;

x = myTest.Test(arg1, ref arg2);
val = Convert.ToDecimal(x.ToString());

if (val == 0)
{
returnString = (string) arg2;
lblLogin.Text = val + returnString;
}


Eric B
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top