Question

I am learning to make DLL for Visual Basic, so I made this:

DLL in C

// FirstDLL.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "stdio.h"

extern "C"
{
    __declspec(dllexport) int sestej(int a, int b)
    {
        int c;
        c = a + b;
        return c;
    }
}

Visual Basic

Public Class Form1

    Declare Function  sestej Lib "C:\Users\Blaž\Documents\Visual Studio     2013\Projects\FirstDLL\Debug\FirstDLL.dll" (ByVal x As Integer, ByVal y As Integer)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim vnos1, vnos2, izhod As Integer

    vnos1 = Convert.ToDecimal(VnosX.Text)
    vnos2 = Convert.ToDecimal(VnosY.Text)

    sestej(vnos1, vnos2)

    lblvsota.Text = izhod

    End Sub
End Class

When I run it I get this error:

An unhandled exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in WindowsApplication2.exe

Additional information: PInvoke restriction: cannot return variants.

I obviously did something wrong but I can't find it anywhere.

Was it helpful?

Solution

When you omit the return type in a VB function, it is assumed to be object. Since object maps to the native VARIANT type, that explains the error. You must specify the return type.

Rather than continue with Declare I suggest you switch to P/invoke. Declare was how it was done in VB6, but P/invoke is the .net way to do interop with unmanaged code. You would declare the function like this:

<DllImport("...\FirstDLL.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function sestej(ByVal a As Integer, _ 
    ByVal b As Integer) As Integer
End Function

This also allows you to correct the other error in your code. Namely the calling convention mismatch. Your unmanaged code uses Cdecl, but your VB code using Declare uses StdCall. The code above fixes that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top