简体   繁体   English

在VB.Net中使用C ++ dll时获取异常

[英]Getting exception while using C++ dll in VB.Net

I have created unmanaged dll and used in VB.Net. 我创建了非托管dll,并在VB.Net中使用。

Both code snippiest is as follows. 这两个代码最简短。

VB.Net VB.Net

Imports System.Text
Imports System.Runtime.InteropServices

Module Module1

    Sub Main()
        Dim c As cls = New cls()
        c.Start()
    End Sub

End Module

Public Class cls
    Declare Sub Only Lib "dllproj2.dll" Alias "Only" (b As StringBuilder)

    Public Sub Start()
        Dim s As StringBuilder = New StringBuilder(15)

        Only(s) '**Actual call to dll code **
        Dim s1 As String = s.ToString.ToLower
        Dim len As Integer = s.ToString.Length.ToString()
        Console.Write(s.ToString())
    End Sub

End Class

C++ dll C ++ dll

#include<stdio.h>
#include<stdlib.h>
#include<cstring>

extern "C"{
void Only(char *a)
{
    char arr[10];

    printf("Reached");
    sprintf(arr,"This %d",33);
    printf("\n%s\n",arr);
    memcpy(a,arr,10);

}
}

Now as soon as I access line Only(s) I get exception shown in image. 现在,只要我访问“ Only(s)Only(s)我就会得到如图所示的异常。

在此处输入图片说明

I am not able to understand cause of exception. 我无法理解异常原因。 Output of code is fine, but while running it using Visual Studio 2012 Express it is giving above error. 代码的输出很好,但是使用Visual Studio 2012 Express运行它时,出现上述错误。

It is sample code, which we also used in production, I afraid it may cause problem in future. 这是示例代码,我们也在生产中使用了它,恐怕将来可能会引起问题。

Kindly suggest is there any way to get rid of exception. 请暗示有什么方法可以摆脱异常。

Thanks. 谢谢。

您必须将b声明为: UnmanagedType.LPStr

Declare Sub Only Lib "dllproj2.dll" Alias "Only" (<InAttribute(), MarshalAs(UnmanagedType.LPStr)> b As StringBuilder)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM