簡體   English   中英

如何通過 CLI/C++ 包裝器使用 C# 中的 byte* 和 int* 參數調用 c++ function

[英]How to call a c++ function with byte* and int* parameters from C# through a CLI/C++ wrapper

我正在嘗試通過 CLI/C++ 包裝器 ZA2F2ED4F8EBC2CBB14C21A2DC 從我的 C# class 調用 c++ 函數我能夠使用編組使用 char* 參數調用 function 。 但是我怎樣才能對參數 int* 做同樣的事情。

//My Native Class
class UNMANAGEDLIB_API CUnmanagedLib {
public:
    CUnmanagedLib(void);
public: void PrintMessage(char* message)
{
    CString StrMessage = message;
    MessageBox(NULL, StrMessage, L"Test Message", MB_OK);
}
public:void IncrementBy2(int* myval)
{
    myval = myval + 2;
}
};

//Wrapper Class
#pragma once
#include "..\UnmanagedLib\UnmanagedLib.h";
using namespace System;
using namespace System::Runtime::InteropServices;
namespace NativeCodeWrapper {
    public ref class Class1
    {
    public: void SendMessageWrapper(String^ strMessage)
    {
        CUnmanagedLib instance;
        char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(strMessage);
        instance.PrintMessage(str2);
    }

    public: void IncrementBy2Wrapper(int* myval)
    {
        CUnmanagedLib instance;
        instance.IncrementBy2(myval);
    }
    };
}

//C# Call
NativeCodeWrapper.Class1 cls = new NativeCodeWrapper.Class1();
//This Works fine
cls.SendMessageWrapper("Hello");

int i = 0;
//How to pass parameter
cls.IncrementBy2Wrapper(???????);

謝謝

首先,原生代碼中定義的“IncrementBy2”方法是錯誤的。

public:void IncrementBy2(int* myval)
{
    myval = myval + 2;
}



如果你想改變變量;

public:void IncrementBy2(int* myval)
{
    *myval = *myval + 2;
    // Or
    // *myval += 2;
}

您是否嘗試過帶有“int%”的“IncrementBy2Wrapper”方法參數?

public: void IncrementBy2Wrapper(int% myval)
{
    CUnmanagedLib instance;
    instance.IncrementBy2((int*)(int&)myval);
}
int i = 0;
//How to pass parameter
//cls.IncrementBy2Wrapper(???????);
cls.IncrementBy2Wrapper(ref i);

暫無
暫無

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

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