2016-11-06 172 views
-1

有沒有什麼辦法可以從c#代碼中調用c代碼?從C#運行C代碼#

我已經讀了很多微軟的文檔中,我已經試過這種方式暫時:

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; 
} 

在此先感謝您。

+1

什麼是 「顯然是行不通的」 呢?錯誤?還有別的嗎? –

+0

無論我做什麼,這部分proc.StartInfo.FileName始終是一個空字符串,所以它只是不運行代碼。 –

+0

您是否試圖執行C源代碼?或者是實際的可執行文件(在這種情況下,寫入哪種語言並不重要,因爲它已被轉換爲機器指令)?或者你想做一些互操作(在這種情況下,PInvoke可能會讓你感興趣)? – UnholySheep

回答

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