簡體   English   中英

從C#調用C ++ dll引發SEHException

[英]calling a C++ dll from C# throwing a SEHException

我正在嘗試從C#代碼調用一個用C ++構建的dll。 但是,我收到以下錯誤:

引發異常:dlltest_client.exe中的“ System.Runtime.InteropServices.SEHException” dlltest_client.exe中發生了類型為“ System.Runtime.InteropServices.SEHException”的未處理異常外部組件引發了異常。

我正在使用cpp代碼構建C ++ dll,而cpp代碼又導入了頭文件:

dlltest.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "dlltest.h"

using namespace std;

// DLL internal state variables:
static string full_;
static string piece_;

void jigsaw_init(const string full_input, const string piece_input)
{
    full_ = full_input;
    piece_ = piece_input;
}

void findPiece()
{
    cout << full_;
    cout << piece_;
}

dlltest.h哪里

#pragma once

#ifdef DLLTEST_EXPORTS
#define DLLTEST_API __declspec(dllexport)
#else
#define DLLTEST_API __declspec(dllimport)
#endif

extern "C" DLLTEST_API void jigsaw_init(
    const std::string full_input, const std::string piece_input);

extern "C" DLLTEST_API void findPiece();

這將成功生成dlltest.dll

我應該利用dll的C#代碼是

dlltest_client.cs

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport(@"path\dlltest.dll")]
    private static extern void jigsaw_init(string full_input, string piece_input);
    [DllImport(@"path\dlltest.dll")]
    private static extern void findPiece();

    static void Main(string[] args)
    {
        string full = @"path\monster_1.png";
        string piece = @"path\piece01_01.png";
        jigsaw_init(full, piece);
        findPiece();
    }
}

您不能將C ++ std::string用於非托管互操作,這是DLL引發異常的原因。

而是使用指向以null終止的字符數組的指針在C#代碼和非托管C ++代碼之間傳遞字符串。

另一個錯誤是C ++代碼使用cdecl調用約定,但是C#代碼采用stdcall。 您需要使界面的兩側匹配,更改一側以匹配另一側。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM