【发布时间】:2014-11-05 13:37:25
【问题描述】:
我对 C++ 比较陌生。出于某种原因,我需要做一个流动模型的工作。
第 1 步:我在 C++ 中有一个 Method1,它将更改从 C# 传递的变量的值。我称该变量为str。
第 2 步:创建一个线程并在几毫秒后将 str 更改为另一个值。
在 C++ 中:
char* temp; // Temporary pointer
void Thread1(void* arr)
{
Sleep(1000); // Wait for one second
strcpy_s(temp, 100, "Thread 1"); // Change value of str to ‘Thread 1’ -> A exception was threw because ‘temp’ is undefined
}
__declspec(dllexport) void Method1(char* str)
{
temp = str; // Keep pointer of ‘str’ to temporary pointer to change ‘str’ value in Thread
strcpy_s(temp, 100, "Method 1"); // Change ‘str’ to ‘Method 1’. -> It work OK
_beginthread(Thread1, 0, NULL); // Start Thread1
}
在 C# 中:
public static StringBuilder str = new StringBuilder(100);
[DllImport("C++.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void Method1(StringBuilder test);
static void Main(string[] args)
{
Method1(str); // Call Method1 in C++ dll.
Console.WriteLine(str.ToString()); // Result: “Method 1” -> OK
while (true)
{
Console.WriteLine(str.ToString()); // Print str value every 0.1 second. It exception after 1 second
Thread.Sleep(100);
}
}
调用Method1时的结果,str变为Method1,但Thread1运行时:指针temp为空,所以抛出异常。
请提供一些关于如何在Thread1 中更改str 的见解。
非常感谢。
【问题讨论】:
标签: c# c++ multithreading