有什么方法可以从C#代码调用C代码?
我一直在阅读许多Microsoft文档,并且暂时尝试过这种方式:
Process proc = new Process();
proc.StartInfo.WorkingDirectory = "path-to-C-code";
proc.StartInfo.FileName = "C-code-name";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
Console.WriteLine(proc.StandardOutput.ReadToEnd());
proc.WaitForExit();
但是显然是行不通的。
无论我做什么,此字符串都将保持为空
proc.StartInfo.FileName
这是C代码,该代码用于杀死自己的进程。
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[], char *env[]) {
int value1;
int value2;
srandom(time(NULL));
switch (random() % 7) {
case 0:
exit(random() % 10);
break;
case 1:
value1 = value1 / (value2 - value2);
break;
case 2:
kill(getpid(), SIGKILL);
break;
case 3:
alarm(random() % 60);
break;
case 4:
__asm__("sti");
break;
case 5:
value1 = *((int*) NULL);
break;
default:
break;
}
return 0;
}
先感谢您。
最佳答案
using System;
using System.Diagnostics;
namespace runGnomeTerminal
{
class MainClass
{
public static void ExecuteCommand(string command)
{
Process proc = new System.Diagnostics.Process ();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
while (!proc.StandardOutput.EndOfStream) {
Console.WriteLine (proc.StandardOutput.ReadLine ());
}
}
public static void Main (string[] args)
{
ExecuteCommand("gnome-terminal -x bash -ic 'cd $HOME; ls; bash'");
}
}
}
感谢J. Piquard
关于c# - 从C#运行C代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446198/