gpt4 book ai didi

c# - 将托管字符串 [] 编码为非托管字符**

转载 作者:太空宇宙 更新时间:2023-11-04 12:25:42 26 4
gpt4 key购买 nike

这是我的 C++ 结构(使用多字节字符集)

typedef struct hookCONFIG {
int threadId;
HWND destination;

const char** gameApps;
const char** profilePaths;
} HOOKCONFIG;

和 .Net 结构

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct HOOKCONFIG {
public int threadId;
public IntPtr destination;

// MarshalAs?
public string[] gameApps;

// MarshalAs?
public string[] profilePaths;
}

我遇到了一些问题,如何编码字符串数组?当我在 C++ 中访问结构变量“profilePaths”时,出现如下错误:

An unhandled exception of type 'System.AccessViolationException' occurred in App.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

MessageBox(0, cfg.profilePaths[0], "Title", MB_OK); // error ... Orz

最佳答案

简单方法:将原型(prototype)更改为 IntPtr[]:

public IntPtr[] gameApps;
public IntPtr[] profilePaths;

现在,当您调用时,您需要大致执行以下伪代码:

GCHandle handle = GCHandle.Alloc(string);
gameApps = new IntPtr[] { GCHandle.ToIntPtr(handle) };

// Unmanaged call

handle.Free();

关于c# - 将托管字符串 [] 编码为非托管字符**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com