2024年1月22日发(作者:)

Process p = new Process();

me = "sh";

llExecute = false;

ctStandardInput = true;

ctStandardOutput = true;

ctStandardError = true;

NoWindow = true;

();

ine("ifconfig eth0 192.168.1.18 netmask 255.255.255.0

");

ine("exit");

string strResult = End();

= strResult;

();

C#调用C函数的方法:

方法一:

1.新建Visual C++类型的Win32项目

C语言的函数定义如下:

extern "C" __declspec(dllexport) int fnTestWin32(void);

实现如下

extern "C" __declspec(dllexport) int fnTestWin32(void)

{

return 42;

}

工程属性页[常规]->[配置类型]选择[动态库.dll]

会生成.lib和.dll文件。用Dependency工具能看到fnTestWin32函数,因为使用了extern "C"

2.C#工程中

[DllImport("", EntryPoint = "fnTestWin32", CharSet = )]

private static extern int fnTestWin32();

把Win32项目生成的dll拷贝到C#生成的exe文件,就可以调用了。

方法二:

1.新建Win32工程

直接使用C语言,函数定义不使用extern "C" __declspec(dllexport)

工程属性页[常规]->[配置类型]选择[静态库(.lib)]

2.新建Visual C++ CLR 类库工程

这里面写的是C++的类,提供给C#直接调用的,作为C与C#的中转,主要使用Marshal类

应用上面的Win32工程,并包含头文件

extern "C"

{

#include "app_notify.h"

}

3.C#工程中直接使用CLR类库工程生成的dll

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

int setlocalip(char *ip)

{

register int fd, intrface;

struct ifreq buf[8];

struct ifconf ifc;

char oldip[16];

struct sockaddr_in addr;

if (ip == NULL)

return -1;

if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >;= 0) {

_len = sizeof buf;

_buf = (caddr_t) buf;

if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) {

intrface = _len / sizeof (struct ifreq);

while (intrface-- >; 0)

{

if (strcmp(buf[intrface].ifr_name, "lo") == 0)

continue;

/*Get IP of the net card */

if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))

{

memset(oldip, 0, sizeof(oldip));

sprintf(oldip, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[intrface ].ifr_addr

))->;sin_addr));

printf("oldip is %sn", oldip);

((struct sockaddr_in*)(&buf[intrface].ifr_addr))->;sin_addr.s_addr = inet_addr(ip);

if (ioctl(fd, SIOCSIFADDR, (char *)&buf[intrface]))

printf("set ip errorn");

}

else {

sprintf (ip, "get ip error");

}

}

}

}

close (fd);

return 0;

}