c++ - 在 VB.Net 中使用 C++ dll 时出现异常

标签 c++ .net vb.net exception interop

我创建了非托管 dll 并在 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++ 动态链接库

#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);

}
}

现在,只要我访问 Only(s) 行,我就会得到图像中显示的异常。

enter image description here

我无法理解异常的原因。代码输出很好,但是在使用 Visual Studio 2012 Express 运行它时出现上述错误。

这是示例代码,我们在生产中也用到了,恐怕以后会出问题。

请建议是否有任何方法可以消除异常。

谢谢。

最佳答案

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

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

关于c++ - 在 VB.Net 中使用 C++ dll 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442571/

相关文章:

c++ - 标记化并转换为 pig latin

c++ - 无需 super 用户即可更改文件权限

C# IEnumerator/yield 结构可能不好?

c# - 从远程客户端接收文件

arrays - 如何在 VB.NET 中声明内联数组

c# - 在 RowCommand 中获取 GridView Cell 的值

c++ - 设计 : How to declare a specialized memory handler class

C++ 运算符技术

c# - 在多个线程上运行 Parallel.Foreach 的性能

vb.net - 我如何获得 Oracle.DataAccess.Client?