首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么C++ DLL不能使用C#封送字符串

为什么C++ DLL不能使用C#封送字符串
EN

Stack Overflow用户
提问于 2019-07-16 01:45:24
回答 1查看 97关注 0票数 1

我在向外部DLL中的某个函数传递字符串时遇到问题。我会张贴一个实际的代码片段,但它有点凌乱,可能很难阅读。以下代码片段是我的个人代码的总和。

C#文件(UNICODE)

[DllImport("InjectDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern ulong FindProgramProcessId(string procName);
[DllImport("InjectDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern bool InjectIntoProcess(ulong procId, string Dll);
string ProcName = "random_test_game.exe";
string DllPath = @"C:\ProgramData\Hack\File.dll";
ulong procId = FindProgramProcessId(ProcName);
bool Injected = InjectIntoProcess(procId, DllPath);

C++文件(ANSI)

DllExport DWORD FindProgramProcessId(const char* procName)
{
    ...
}
DllExport bool InjectIntoProcess(DWORD procId, const char* Dll)
{
    if (Dll == nullptr)
    {
        MessageBox(NULL, "DLL", "EMPTY", MB_OK);
        return false;
    }
    ...
}

C++头文件

#pragma once
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
#ifdef EXPORT
#define DllExport __declspec(dllexport)
#else
#define DllExport __declspec(dllimport)
#endif
extern "C" DllExport DWORD FindProgramProcessId(const char* procName);
extern "C" DllExport bool InjectIntoProcess(DWORD procId, const char* Dll);

参考这些代码片段,出现的问题是FindProgramProcessId将成功传递一个字符串,没有问题,但是根据我在该方法中添加的“额外”代码,InjectIntoProcess会将const char* Dll显示为nullptr

请注意,我已经尝试用IntPtr代替string并使用Marshal.StringToHGlobalAnsi,但仍然遇到Dll == nullptr问题。它破坏了我的准则。更多相同的信息可以在我的GuidedHacking线程中找到。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-16 03:11:52

Win32 DWORD是32位整数,但C# ulong是64位整数。混淆源于这样一个事实:DWORDunsigned long的别名,但C++ long不一定是64位的(实际上,在MSVC中,它是32位;unsigned long long是64位的无符号整数)。

由于您使用的是cdecl调用约定,因此调用者负责清理堆栈(因此不会发生崩溃),参数是从右到左传递的(因此Dll最终指向传递给cdecl的值的中间位置,该值可能包含零)。至少这是我的猜测,因为我们在这里处于未定义的行为领域。

您应该改为将FindProgramProcessId的返回值和InjectIntoProcessprocId参数声明为uint

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57044791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档