我對C++比較陌生。出於某種原因,我需要做一個流動模型的工作。從C調用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
的信息。
非常感謝。