试图在C#中使用C ++的LPTSTR [英] Trying to use LPTSTR of C++ in C#

查看:321
本文介绍了试图在C#中使用C ++的LPTSTR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

系统抛出异常

The system throws exception

System.NullReferenceException: 'Object reference not set to an instance of an object.'



如果有人知道解决方案,请帮助



我尝试过:



我正在尝试使用ccs函数将LPTStr返回到c#

这是我的dll.cpp文件


If anyone knows solution kindly help

What I have tried:

I am trying to use a c++ function that return LPTStr into c#
This is my dll.cpp file

;extern "C" __declspec(dllexport) LPTSTR PID_GetProcessName(int a) {

	DWORD aProcesses[1024], cbNeeded, cProcesses;
	unsigned int i;
	EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
	if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
	{
		return NULL;
	}


	// Calculate how many process identifiers were returned.

	cProcesses = cbNeeded / sizeof(DWORD);
	TCHAR szProcessName[MAX_PATH];

	// Get a handle to the process.
	for (int i = 0; i <= cProcesses; i++)
		if (i == a) {
			HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
				PROCESS_VM_READ,
				FALSE, aProcesses[i]);

			// Get the process name.

			if (NULL != hProcess)
			{
				HMODULE hMod;
				DWORD cbNeeded;

				if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
					&cbNeeded))
				{
					GetModuleBaseName(hProcess, hMod, szProcessName,
						sizeof(szProcessName) / sizeof(TCHAR));
					LPTSTR b = szProcessName;
					return b;
				}
			}
			
			CloseHandle(hProcess);
			break;
		}
}



这是我的c#代码


This is my c# code

[DllImport("D:\\RunningProcessDll\\Debug\\RunningProcessDll.dll",
             CallingConvention = CallingConvention.Cdecl)]
[return : MarshalAs(UnmanagedType.LPTStr)]
        public static extern string PID_GetProcessName(int a);

推荐答案

错误消息显示实际情况:您的函数在第一个出口返回NULL最后没有。



1.如果你返回NULL,你必须在你的C#代码中检查并处理它。

2 。在你的函数结束时,你还必须返回一个值,也许与案例1分开。
The error message shows you the reality: Your function is return at the first exit a NULL and NOTHING at the end.

1. if you return NULL than you must check it in your C# code and handle it.
2. at the end of your function you must also return a value, maybe "" to separate from case 1.


这篇关于试图在C#中使用C ++的LPTSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆