c# - 将字符串从 c# 传递到 c++ dll

标签 c# c++ pinvoke

我正在尝试将字符串从 C# 传递到 C++ dll。我在 dll 中收到的字符串是一些奇怪的字符。这是我的代码。

在 C++ dll 中:

#include "stdafx.h"
#include <tlhelp32.h>
#include <tchar.h>
#include "ProcessCheckerDll.h"
#include <fstream>
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <psapi.h>
#include "Shlwapi.h"
#include <string>
#include <windows.h>


namespace ProcessCheck
{
string GetRunningProcessFromHierarchy(char* argStrRoot)
{ 
    char ch;
    printf("Reached here 1.");
    scanf_s("%c",&ch);

    std::string strRoot(argStrRoot,strlen(argStrRoot));
    printf_s("strRoot = %s",strRoot);
    std::ifstream input("d:\\filelist.txt");
    std::string line;

    printf("Reached here 2.");
    scanf_s("%c",&ch);

    //printf("cdsroot=%ls",strRoot);

    std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), ::tolower);
    std::vector<std::string> collection;
    string result="";


    printf("Reached here 3.");
    scanf_s("%c",&ch);

    HANDLE hProcessSnap=nullptr;
    HANDLE hProcess;
    PROCESSENTRY32 pe32;
    DWORD dwPriorityClass;


    while( std::getline( input, line ) )
    {
        //Get the file name from path
        std::wstring strPathFromTextFile = std::wstring(line.begin(), line.end());
        LPCWSTR absolutePathToFile = strPathFromTextFile.c_str();
        LPCWSTR onlyFileName = PathFindFileName(absolutePathToFile); 

        // Take a snapshot of all processes in the system.
        hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if(hProcessSnap == INVALID_HANDLE_VALUE)
        {
            printf("Failed to get the snapshot of running processes");
            return result;
        }

        pe32.dwSize = sizeof(PROCESSENTRY32);

        // Retrieve information about the first process and exit if unsuccessful
        if(!Process32First(hProcessSnap, &pe32))
        {
            printf("Failed to get the first process from the list");
            CloseHandle(hProcessSnap);     // clean the snapshot object
            return result;
        }

        // Now walk the snapshot of processes, and display information about each process in turn
        do
        {
            LPCWSTR processFileName = pe32.szExeFile;

            if(lstrcmpi(onlyFileName,processFileName)==0)
            {
                //If file name is same, check if path starts with cdsroot
                HANDLE processHandle = NULL;
                TCHAR filePath[MAX_PATH];

                processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID);


                if (processHandle != NULL)
                {
                    if (GetModuleFileNameEx(processHandle, NULL, filePath, MAX_PATH) == 0)
                    {
                        printf("\nFailed to get module filename.");
                    }
                    else
                    {
                        std::wstring w_str(filePath);
                        std::string absolutePath(w_str.begin(), w_str.end());
                        std::transform(absolutePath.begin(), absolutePath.end(), absolutePath.begin(), ::tolower);

                        printf_s("Absolute path = %s", absolutePath);
                        printf_s("Matching with cdsroot = %s",strRoot);
                        if(absolutePath.find(strRoot)==0)
                        {
                            std::wstring processName(processFileName);
                            std::string strProcess(processName.begin(),processName.end());
                            printf_s("\nROOT match for Process name = %s",strProcess);

                            if (std::find(collection.begin(), collection.end(), strProcess) == collection.end())
                            {
                                collection.push_back(strProcess);
                                printf_s("\nAdding to collection Process name = %s",strProcess);
                                result = result + strProcess + ";";
                            }
                        }
                    }
                    CloseHandle(processHandle);
                }
                else
                {
                    printf("\nFailed to open process.");
                }
            }
        }
        while(Process32Next(hProcessSnap, &pe32));
    }

    CloseHandle(hProcessSnap);
    printf("Returning result %s", result);
    scanf_s("%c",&ch);
    return result;
}
}

头文件包含:

#include <stdexcept>
#include <vector>
using namespace std;

namespace ProcessCheck
{
extern "C" { __declspec(dllexport) string GetRunningProcessFromHierarchy(char* argStrRoot); }
}

C#中的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace ProcCheckTest
{
class Program
{

    [DllImport("C:\\Users\\himanshu\\Documents\\Visual Studio 2012\\Projects\\ProcessCheck\\Release\\ProcessCheckerDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern string GetRunningProcessFromHierarchy([MarshalAs(UnmanagedType.LPStr)] string strRoot);

    static void Main(string[] args)
    {
        string strRoot = "C:\\test\\today_16.6";
        string returnValue = GetRunningProcessFromHierarchy(strRoot);
    }
}
}

我传递的字符串是“C:\test\today_16.6”,但是当我在 dll 代码中打印相同的字符串时,它会打印出奇怪的字符。 这里有什么问题?

最佳答案

主要问题似乎在这里:

printf_s("strRoot = %s",strRoot);

问题是 strRootstd::string 类型,但格式字符串需要 char*。将其更改为:

printf_s("strRoot = %s",strRoot.c_str());

或者直接使用argStrRoot

您的另一个问题是函数的返回值。当前您返回 std::string。你不能用 p/invoke 编码它。您需要返回 char*。更重要的是,就目前而言,编码器将在它接收到的指针上调用 CoTaskMemFree 作为返回值。因此,您需要分配使用 CoTaskMemAlloc 返回的 char*

关于c# - 将字符串从 c# 传递到 c++ dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25617620/

相关文章:

c# - 在某些情况下,如何在需要空指针的 P/Invoke 签名中使用 SafeHandle?

c# - CollisionOnEnter 如何检测物体是否发生碰撞?

c# - 如何让grpc像WCF一样抛出原始异常?

c++ - 如何找到正在运行的进程的物理套接字 ID/编号?

c# - 调用 native C++ 方法时在 Debug模式 (F5) 下崩溃

c# - P/Invoke Interop Assistant - 是否像导入 dll 的 header 一样简单?

c# - Windows Phone 8异常中检测到布局循环?

c# - 如何将UTC时间转换为C#中任何其他时区的时间

c++ - C++ 中的模板和高阶种类

c++ - 递归似乎仅在某种程度上起作用-如何调试此类问题?