2010年7月7日星期三

see all running process in Linux

How do I see all running process in Linux?

You need to use the ps command. It provide information about the currently running processes, including their process identification numbers (PIDs). Both Linux and UNIX support ps command to display information about all running process. ps command gives a snapshot of the current processes. If you want a repetitive update of this status, use top command.

ps command

Type the following ps command to display all running process:
# ps aux | less

Where,

  • -A: select all processes
  • a: select all processes on a terminal, including those of other users
  • x: select processes without controlling ttys

Task: see every process on the system

Abstract Class in Java (reproduced)

Abstract Methods and Classes
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

Note: All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be—it's just not necessary).

Abstract Classes versus Interfaces

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

An Abstract Class Example

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for example: position, orientation, line color, fill color) and behaviors (for example: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects—for example: position, fill color, and moveTo. Others require different implementations—for example, resize or draw. All GraphicObjects must know how to draw or resize themselves; they just differ in how they do it. This is a perfect situation for an abstract superclass. You can take advantage of the similarities and declare all the graphic objects to inherit from the same abstract parent object—for example, GraphicObject, as shown in the following figure.

Classes Rectangle, Line, Bezier, and Circle inherit from  GraphicObject

Classes Rectangle, Line, Bezier, and Circle inherit from GraphicObject

First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declares abstract methods for methods, such as draw or resize, that need to be implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:

abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods:
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

When an Abstract Class Implements an Interface

In the section on Interfaces , it was noted that a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. For example,
abstract class X implements Y {
// implements all but one method of Y
}

class XX extends X {
// implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.

Class Members

An abstract class may have static fields and static methods. You can use these static members with a class reference—for example, AbstractClass.staticMethod()—as you would with any other class.

2010年7月6日星期二

Multi-threaded Debugging Techniques By Shameem Akhter and Jason Roberts, April 23, 2007


Shameem Akhter is a platform architect at Intel Corporation, focusing on single socket multi-core architecture and performance analysis. Jason Roberts is a senior software engineer at Intel, and has worked on a number of different multi-threaded software products that span a wide range of applications targeting desktop, handheld, and embedded DSP platforms. This article was excerpted from their book Multi-Core Programming. Copyright (c) 2006 Intel Corporation. All rights reserved.

Debugging multi-threaded applications can be a challenging task. The increased complexity of multi-threaded programs results in a large number of possible states that the program may be in at any given time. Determining the state of the program at the time of failure can be difficult; understanding why a particular state is troublesome can be even more difficult. Multi-threaded programs often fail in unexpected ways, and often in a nondeterministic fashion. Bugs may manifest themselves in a sporadic fashion, frustrating developers who are accustomed to troubleshooting issues that are consistently reproducible and predictable. Finally, multi-threaded applications can fail in a drastic fashion-deadlocks cause an application or worse yet, the entire system, to hang. Users tend to find these types of failures to be unacceptable.

General Debug Techniques

Regardless of which library or platform that you are developing on, several general principles can be applied to debugging multi-threaded software applications.

The first technique for eliminating bugs in multi-threaded code is to avoid introducing the bug in the first place. Many software defects can be prevented by using proper software development practices. The later a problem is found in the product development lifecycle, the more expensive it is to fix. Given the complexity of multi-threaded programs, it is critical that multi-threaded applications are properly designed up front.

How often have you, as a software developer, experienced the following situation? Someone on the team that you're working on gets a great idea for a new product or feature. A quick prototype that illustrates the idea is implemented and a quick demo, using a trivial use-case, is presented to management. Management loves the idea and immediately informs sales and marketing of the new product or feature. Marketing then informs the customer of the feature, and in order to make a sale, promises the customer the feature in the next release. Meanwhile, the engineering team, whose original intent of presenting the idea was to get resources to properly implement the product or feature sometime in the future, is now faced with the task of delivering on a customer commitment immediately. As a result of time constraints, it is often the case that the only option is to take the prototype, and try to turn it into production code.

While this example illustrates a case where marketing and management may be to blame for the lack of following an appropriate process, software developers are often at fault in this regard as well. For many developers, writing software is the most interesting part of the job. There's a sense of instant gratification when you finish writing your application and press the run button. The results of all the effort and hard work appear instantly. In addition, modern debuggers provide a wide range of tools that allow developers to quickly identify and fix simple bugs. As a result, many programmers fall into the trap of coding now, deferring design and testing work to a later time. Taking this approach on a multi-threaded application is a recipe for disaster for several reasons:

  • Multi-threaded applications are inherently more complicated than single-threaded applications. Hacking out a reliable, scalable implementation of a multi-threaded application is hard; even for experienced parallel programmers. The primary reason for this is the large number of corner cases that can occur and the wide range of possible paths of the application. Another consideration is the type of run-time environment the application is running on. The access patterns may vary wildly depending on whether or not the application is running on a single-core or multi-core platform, and whether or not the platform supports simultaneous multithreading hardware. These different run-time scenarios need to be thoroughly thought out and handled to guarantee reliability in a wide range of environments and use cases.

  • Multi-threaded bugs may not surface when running under the debugger. Multi-threading bugs are very sensitive to the timing of events in an application. Running the application under the debugger changes the timing, and as a result, may mask problems. When your application fails in a test or worse, the customer environment, but runs reliably under the debugger, it is almost certainly a timing issue in the code. While following a software process can feel like a nuisance at times, taking the wrong approach and not following any process at all is a perilous path when writing all but the most trivial applications. This holds true for parallel programs. While designing your multi-threaded applications, you should keep these points in mind.

  • Design the application so that it can run sequentially. An application should always have a valid means of sequential execution. The application should be validated in this run mode first. This allows developers to eliminate bugs in the code that are not related to threading. If a problem is still present in this mode of execution, then the task of debugging reduces to single-threaded debugging. In many circumstances, it is very easy to generate a sequential version of an application. For example, an OpenMP application compiled with one of the Intel compilers can use the openmp-stubs option to tell the compiler to generate sequential OpenMP code.

  • Use established parallel programming patterns. The best defense against defects is to use parallel patterns that are known to be safe. Established patterns solve many of the common parallel programming problems in a robust manner. Reinventing the wheel is not necessary in many cases.

  • Include built-in debug support in the application. When trying to root cause an application fault, it is often useful for programmers to be able to examine the state of the system at any arbitrary point in time. Consider adding functions that display the state of a thread-or all active threads. Trace buffers, described in the next section, may be used to record the sequence of accesses to a shared resource. Many modern debuggers support the capability of calling a function while stopped at a breakpoint. This mechanism allows developers to extend the capabilities of the debugger to suit their particular application's needs.

2010年7月5日星期一

大数阶乘

大数的操作问题,用基本的数据类型都有溢出的风险。在此,介绍一种比较好的思路,来计算大数的阶乘,比如。100!

首先,定义两个整型的数组:
int fac[1000];//暂且先设定是1000位,我称之为“结果数组”
int add[1000];//我称之为“进位数组”

现在具体说明两个数组的作用:

1.fac[1000]
比如说,一个数5的阶乘是120,那么我就用这个数组存储它:
fac[0]=0
fac[1]=2
fac[2]=1
现在明白了数组 fac的作用了吧。用这样的数组我们可以放阶乘后结果是1000位的数。

2.在介绍add[1000]之前,我介绍一下算法的思想,就以 6!为例:
从上面我们知道了5!是怎样存储的。
就在5!的基础上来计算6!,演示如下:

fac[0]=fac[0]*6=0
fac[1]=fac[1]*6=12
fac[2]=fac[2]*6=6

3. 现在就用到了我们的:“进位数组”add[1000].
先得说明一下:add[i]就是在第2步中用算出的结果中,第i位向第i+1位的进位数值。还是接上例:
add[0]=0;
add[1]=1; // 计算过程:就是 (fac[1]+add[0]) / 10=1
add[2]=0; // 计算过程:就是 (fac[2]+add[1]) /10=0
.......
.......
.......

add[i+1] =( fac[i+1] + add[i] ) / 10

现在就知道了我们的数组add[]是干什么的了吧,并且明白了add[i]是如何求得的了吧。



4.知道了add[1000]的值,现在就在 1. 和 3 . 两步的基础上来计算最终的结果。(第2步仅作为我们理解的步骤,我们下面的计算已经包含了它)

fac[0] = ( fac[0]*6 ) mod 10 =0
fac[1] = ( fac[1]*6 + add[0] ) mod 10 =2
fac[2] = ( fac[2]*6 + add[1] ) mod 10=7

到这里我们已经计算完了6!。然后就可以将数组fac[1000]中的数,以字符的形式按位输出到屏幕上了。

5.还有一点需要说明,就是我们需要一个变量来记录fac[1000]中实际用到了几位,比如5!用了前 3位;
我们在这里定义为 top
为了计算top,我们有用到了add[1000],还是以上面的为例:

5!时,top=3,在此基础上我们来看6!时top=?
由于 add[2]=0
所以 top=3(没有变)
也就是说,如果最高位有进位时,我们的top=top+1,否则,top值不变。

6.总结一下,可以发现,我们把阶乘转化为 两个10以内的数的乘法,还有两个10以内的数的家法了。
因此,不管再大的数,基本上都能算出了,只要你的数组够大就行了。

程序实现:

#include "stdafx.h"
#include

using namespace std;

#define MAX 1000

int fac[MAX]={1,};
int add[MAX]={0,};

int top=1;//计算结果位数

void calculate(int n);

void print();

int main(int argc, char * argv[])
{
cout<<"please input the number:"; int n; cin>>n;
calculate(n);
cout<<<"!="; print(); cout<<" 总共"<<<"位"<<=0) { exit(1); } for (int i=1;i<=n;i++) { int m=top; for (int j=0;j0){
top++;
int tmp=fac[top-1];
fac[top-1]=(tmp+add[top-2])%10;
add[top-1]=(tmp+add[top-2])/10;
}
}
}
}

// 打印输出结果
void print(){
int j=0;
for(int i=top-1;i>=0;i--)
{
if ((j++)%20==0)
{
cout<
}
cout<
}
cout<
}

2010年6月27日星期日

C++ interview questions

C/C++ Programming interview questions and answers

By Satish Shetty, July 14th, 2004

What is encapsulation??

Containing and hiding information about an object, such as internal data structures and code. Encapsulation isolates the internal complexity of an object's operation from the rest of the application. For example, a client component asking for net revenue from a business object need not know the data's origin.

What is inheritance?

Inheritance allows one class to reuse the state and behavior of another class. The derived class inherits the properties and method implementations of the base class and extends it by overriding methods and adding additional properties and methods.

What is Polymorphism??

Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.

You can use implementation inheritance to achieve polymorphism in languages such as C++ and Java.

Base class object's pointer can invoke methods in derived class objects.

You can also achieve polymorphism in C++ by function overloading and operator overloading.

What is constructor or ctor?

Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.

What is destructor?

Destructor usually deletes any extra resources allocated by the object.

What is default constructor?

Constructor with no arguments or all the arguments has default values.

What is copy constructor?

Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.

for example:
Boo Obj1(10); // calling Boo constructor

Boo Obj2(Obj1); // calling boo copy constructor
Boo Obj2 = Obj1;// calling boo copy constructor

When are copy constructors called?

Copy constructors are called in following cases:
a) when a function returns an object of that class by value
b) when the object of that class is passed by value as an argument to a function
c) when you construct an object based on another object of the same class
d) When compiler generates a temporary object

What is assignment operator?

Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)

What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don't define one.??

default ctor
copy ctor
assignment operator
default destructor
address operator

What is conversion constructor?

constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.

for example:

class Boo
{
public:
Boo( int i );
};

Boo BooObject = 10 ; // assigning int 10 Boo object

What is conversion operator??

class can have a public method for specific data type conversions.

for example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};

Boo BooObject;

double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.

What is diff between malloc()/free() and new/delete?

malloc allocates memory for object in heap but doesn't invoke object's constructor to initiallize the object.

new allocates memory and also invokes constructor to initialize the object.

malloc() and free() do not support object semantics
Does not construct and destruct objects
string * ptr = (string *)(malloc (sizeof(string)))
Are not safe
Does not calculate the size of the objects that it construct
Returns a pointer to void
int *p = (int *) (malloc(sizeof(int)));
int *p = new int;
Are not extensible
new and delete can be overloaded in a class

"delete" first calls the object's termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []:-

Int_t *my_ints = new Int_t[10];

...

delete []my_ints;

what is the diff between "new" and "operator new" ?


"operator new" works like malloc.

What is difference between template and macro??

There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.

If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times.

Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.

for example:

Macro:

#define min(i, j) (i < j ? i : j)

template:
template
T min (T i, T j)
{
return i < j ? i : j;
}



What are C++ storage classes?

auto
register
static
extern

auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block

register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance

static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution

extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.

What are storage qualifiers in C++ ?

They are..

const
volatile
mutable

Const keyword indicates that memory once initialized, should not be altered by a program.

volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.

mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

struct data
{
char name[80];
mutable double salary;
}

const data MyStruct = { "Satish Shetty", 1000 }; //initlized by complier

strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

What is reference ??

reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object.

prepending variable with "&" symbol makes it as reference.

for example:

int a;
int &b = a;


What is passing by reference?

Method of passing arguments to a function which takes parameter of type reference.

for example:

void swap( int & x, int & y )
{
int temp = x;
x = y;
y = temp;
}

int a=2, b=3;

swap( a, b );

Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.


When do use "const" reference arguments in function?

a) Using const protects you against programming errors that inadvertently alter data.
b) Using const allows function to process both const and non-const actual arguments, while a function without const in the prototype can only accept non constant arguments.
c) Using a const reference allows the function to generate and use a temporary variable appropriately.


When are temporary variables created by C++ compiler?

Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways.

a) The actual argument is the correct type, but it isn't Lvalue

double Cube(const double & num)
{
num = num * num * num;
return num;

}

double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;

b) The actual argument is of the wrong type, but of a type that can be converted to the correct type

long temp = 3L;
double value = cuberoot ( temp); // long to double conversion


What is virtual function?

When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.

class parent
{
void Show()
{
cout << "i'm parent" << endl;
}
};

class child: public parent
{
void Show()
{
cout << "i'm child" << endl;
}

};

parent * parent_object_ptr = new child;

parent_object_ptr->show() // calls parent->show() i

now we goto virtual world...

class parent
{
virtual void Show()
{
cout << "i'm parent" << endl;
}
};

class child: public parent
{
void Show()
{
cout << "i'm child" << endl;
}

};

parent * parent_object_ptr = new child;

parent_object_ptr->show() // calls child->show()


What is pure virtual function? or what is abstract class?

When you define only function prototype in a base class without implementation and do the complete implementation in derived class. This base class is called abstract class and client won't able to instantiate an object using this base class.

You can make a pure virtual function or abstract class this way..

class Boo
{
void foo() = 0;
}

Boo MyBoo; // compilation error


What is Memory alignment??

The term alignment primarily means the tendency of an address pointer value to be a multiple of some power of two. So a pointer with two byte alignment has a zero in the least significant bit. And a pointer with four byte alignment has a zero in both the two least significant bits. And so on. More alignment means a longer sequence of zero bits in the lowest bits of a pointer.

What problem does the namespace feature solve?

Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.

namespace [identifier] { namespace-body }

A namespace declaration identifies and assigns a name to a declarative region.
The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.

What is the use of 'using' declaration?

A using declaration makes it possible to use a name from a namespace without the scope operator.

What is an Iterator class?

A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. Something like a pointer.

What is a dangling pointer?

A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

What do you mean by Stack unwinding?

It is a process during exception handling when the destructor is called for all local objects in the stack between the place where the exception was thrown and where it is caught.

Name the operators that cannot be overloaded??

sizeof, ., .*, .->, ::, ?:

What is a container class? What are the types of container classes?

A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

What is inline function??

The __inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler's discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline.


What is overloading??

With the C++ language, you can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope.

- Any two functions in a set of overloaded functions must have different argument lists.
- Overloading functions with argument lists of the same types, based on return type alone, is an error.

What is Overriding?

To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list.
The definition of the method overriding is:
· Must have same method name.
· Must have same data type.
· Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class.

What is "this" pointer?

The this pointer is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.

When a nonstatic member function is called for an object, the address of the object is passed as a hidden argument to the function. For example, the following function call

myDate.setMonth( 3 );

can be interpreted this way:

setMonth( &myDate, 3 );

The object's address is available from within the member function as the this pointer. It is legal, though unnecessary, to use the this pointer when referring to members of the class.

What happens when you make call "delete this;" ??

The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.

You should never do this. Since compiler does not know whether the object was allocated on the stack or on the heap, "delete this" could cause a disaster.

How virtual functions are implemented C++?

Virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed first which creates the vtable. If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions

What is name mangling in C++??

The process of encoding the parameter types with the function/method name into a unique name is called name mangling. The inverse process is called demangling.

For example Foo::bar(int, long) const is mangled as `bar__C3Fooil'.
For a constructor, the method name is left out. That is Foo::Foo(int, long) const is mangled as `__C3Fooil'.

What is the difference between a pointer and a reference?

A reference must always refer to some object and, therefore, must always be initialized; pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.

How are prefix and postfix versions of operator++() differentiated?

The postfix version of operator++() has a dummy parameter of type int. The prefix version does not have dummy parameter.

What is the difference between const char *myPointer and char *const myPointer?

Const char *myPointer is a non constant pointer to constant data; while char *const myPointer is a constant pointer to non constant data.

How can I handle a constructor that fails?

throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

How can I handle a destructor that fails?

Write a message to a log-file. But do not throw an exception.
The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding.
During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bar e) { handler? There is no good answer -- either choice loses information.
So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you're dead.

What is Virtual Destructor?

Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes.

if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.


Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?

C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.

Name two cases where you MUST use initialization list as opposed to assignment in constructors.

Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them.

Can you overload a function based only on whether a parameter is a value or a reference?

No. Passing by value and by reference looks identical to the caller.

What are the differences between a C++ struct and C++ class?

The default member and base class access specifiers are different.

The C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance.

What does extern "C" int func(int *, Foo) accomplish?

It will turn off "name mangling" for func so that one can link to code compiled by a C compiler.

How do you access the static member of a class?

::

What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?

Multiple Inheritance is the process whereby a child can be derived from more than one parent class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classes implement a method with the same name.

What are the access privileges in C++? What is the default access level?

The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.

What is a nested class? Why can it be useful?

A nested class is a class enclosed within the scope of another class. For example:

// Example 1: Nested class
//
class OuterClass
{
class NestedClass
{
// ...
};
// ...
};
Nested classes are useful for organizing code and controlling access and dependencies. Nested classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is public then any code can name it as OuterClass::NestedClass. Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass's members and friends can use NestedClass.

When you instantiate as outer class, it won't instantiate inside class.

What is a local class? Why can it be useful?

local class is a class defined within the scope of a function -- any function, whether a member function or a free function. For example:

// Example 2: Local class
//
int f()
{
class LocalClass
{
// ...
};
// ...
};
Like nested classes, local classes can be a useful tool for managing code dependencies.


Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?


No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.

if you have any comments/questions please email me at

copyright (c) 2004, Satish Shetty, All rights reserved,

visit my homepage at http://www.shettysoft.com

2010年1月19日星期二

some good sentences for paper writing

1 precision and recall experiment should be conducted to see whether this method can actually improve the quality of the final ranking list
2 about the similarity threshold, the threshold is relied on the user to set it. However, how such threshold should be set is not clearly illustrated.
3 The authors of this paper tried to address a new problem, of developing a new distance measure for subtrees, which has not been proposed / solved before

4 and avoided the drawbacks of total mapping

5 there is just one sentence mentioning a very important information, and no further illustration is presented later

6 the authors claimed that

7 However, such claim is not convincing, and more details and illustration are needed to convince the reader that the efficiency of the PPI is really OK, and this should also be demonstrated in the later experiment section

8 This paper identified two critical problems/drawbacks of previous works

9 decreasing the page rank of spam sites could be directly achieved by using previous work

10 We three reviewers agree with some weak points of the paper, such as unavailability of category tags for most of the pages, the to-be-improved presentation and in-comprehensive experiment.

the which is not significant.



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
some points in writing the
1 Do NOT start a sentence with “AND”. I have said this many times, and hope this is the last time.also not add the First
2 A paper must be consistent, so does a review.Not enough pages should not count as a weak point to reject paper
3 author+"proposed to"
4 "presents" should be "represent"
5 be concise
6 explain that why
7 method->technique

////////////////////////////////////////////////
major problem:
1

2 's and in the begining

////////////////////////////////////////////
question: to merge them?

2009年11月3日星期二

c++ Precedence

http://www.cppreference.com/wiki/operator_precedencet

2009年10月27日星期二

C# string processing

trim-> only deal with the case related to the beginning and the end
replace-> can deal with the case in the middle

2009年7月8日星期三

Java' List +template

ArrayList m =new ArrayList();
List minPath =m.subList(0, 0);


Java' s List class even can not initialize with the templete, feeling weird about it.

2009年7月1日星期三

my sql database population

1 add bar as the database or table name
SQL_MODE=ANSI_QUOTES
2

2007年5月29日星期二

ASP.NET调用DLL(C#)

首先建立一个bin文件夹,然后将dll文件拷贝到该bin文件夹下,
然后在程序里使用
using namespace;
或者
<%@ import namespace="your-namespace" %>
的方式导入该命名空间,接下来就可以使用dll里面的函数了。


、创建C# 类库 (Dll)
以前在VC++中创建一个dll文件不能说简单,但在Visual C# 中,这将同样是轻而易举的事情。下面的介绍分成两部分:1、创建DLL,2、在客户端测试dll。
(1)创建DLL
首先创建一个空的类库工程。在VS.NET集成环境(IDE)中选择“文件->新建->工程文件->Visual C# 工程->类库”,点击Browse(浏览)按钮选择工程文件名和相应的目录,再点击 OK。
接着看看工程和它的相关文件。Solution Explorer(解决方案探测器)向工程中增加两个C# 类,第一个是 AssemblyInfo.cs ,第二个是Class1.cs。我们不讨论AssemblyInfo,重点介绍 Class1.cs。


双击Class1.cs,就能看到一个名称空间mcMath。我们将在客户机引用这个名称空间以使用这个类库:
namespace mcMath
{
using System;
///
/// Summary description for Class1.
///

public class Class1
{
public Class1()
{
//
// TODO: Add Constructor Logic here
//
}
}
}
现在就可以Build(构造)这个工程了。Build(构造)完毕后,就会在工程文件的bin/debug 目录中生成mcMath.dll文件。
增加一个方法
从View (视图)菜单中打开ClassView(类视图),开始只显示Class1,没有方法和属性。现在来增加一个方法和一个属性。
用鼠标右键单击“Class1”,选择“Add(增加)-> Add Method(增加方法)”,这时将弹出C# 方法生成向导:


在这个窗口中增加方法名、存取类型、返回类型、参数以及注释信息。使用Add(增加)和Remove(取消)按钮可分别从参数列表中增加和取消参数。这里增加了一个方法long Add( long val1, long val2 ),它负责将两个数字相加并返回和。
增加一个属性
同理可以通过C#属性生成向导,向类中增加一个属性:


增加了一个方法和一个属性后, Class1变成下图所示的样子:


仔细观察这个 Class1,你会发现C#的向导程序向类中增加了如下两个函数:
public long Add (long val1, long val2)
{
return 0;
}

public bool Extra
{
get
{
return true;
}
set
{
}
}
向类中增加代码
这里把Class1修改成为 mcMathComp ,因为 Class1是个容易造成混淆的名字,当想将这个类用在一个客户应用程序中时会造成问题。下面的代码对上面的做了些调整:
namespace mcMath
{
using System;
public class mcMathComp
{
private bool bTest = false;
public mcMathComp()
{
}
public long Add (long val1, long val2)
{
return val1 + val2;
}
public bool Extra
{
get
{
return bTest;
}
set
{
bTest = Extra ;
}
}
}
}
构造 dll
选择Build菜单创建dll文件,如果一切OK,就会在工程文件的 bin\debug目录生成dll文件。
(2)在客户端测试 dll
在客户端调用dll的方法和属性也是非常简单的工作,请遵照下面的步骤执行:
① 创建控制台应用程序
在VS.NET IDE集成环境中选择“文件-> 新建->工程文件->Visual C#工程文件->控制台应用程序”,最终将在这个控制台应用程序中测试dll。
② 增加名称空间的引用
选择“工程->添加引用”(Project->Add reference),然后浏览文件找到dll,点击 Ok:




引用添加向导程序将向当前工程文件中增加对相关库的引用:


③ 调用mcMath名称空间,创建 mcMathComp 的对象,并调用其方法和属性。
现在距离调用组件的方法和属性只有一步之遥了。请按照以下步骤进行:
●引用名称空间:using mcMath
●创建一个 mcMathComp的对象:mcMathComp cls = new mcMathComp();
●调用方法和属性
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;
以下是完整的工程文件代码:
namespace mcClient
{
using System;
using mcMath;
///
/// Summary description for Class1.
///

public class Class1
{
public Class1()
{
//
// TODO: Add Constructor Logic here
//
}
public static int Main(string[] args)
{
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;
return 0;
}
}

IIS报Service Unavailable错的解决方案

过检测,发现我的windows2003的应用程序池被改成DefaultAppPool了!改成原来的MsSharePointAppPool就可以了。

转载一篇详细的文章:

浏览 Windows SharePoint Services Web 站点时收到“Service Unavailable”(服务不可用)错误信息

症状
当您浏览一个 Windows SharePoint Services Web 站点时,您可能会收到下面的错误信息:
Service Unavailable
原因
如果 Microsoft Internet 信息服务 (IIS) 6.0 中没有正确地配置用于虚拟服务器的应用程序池,就可能会发生此问题。此问题可能会在存在下列一种或多种情况时发生: •应用程序池没有运行。
•应用程序池帐户使用的密码不正确。
•应用程序池帐户不是服务器上的 IIS_WPG 和 STS_WPG 这两个组的公共成员。

解决方案
要解决此问题,请按照下列步骤操作: 1.验证是否已为虚拟服务器配置了应用程序池。默认的应用程序池是 MSSharePointPortalAppPool。

请按照下列步骤来确定虚拟服务器正在使用的应用程序池。 a. 单击“开始”,指向“管理工具”,然后单击“Internet 信息服务 (IIS) 管理器”。
b. 展开“ServerName”,展开“Web 站点”,右键单击虚拟服务器,然后单击“属性”。
c. 单击“主目录”选项卡。

为虚拟服务器配置的应用程序池列在“应用程序池”框中。
d. 单击“确定”。

2.验证应用程序池帐户使用的密码是否正确。IIS 不会自动轮询 Active Directory 目录服务中的密码更改。如果应用程序池帐户是一个域帐户,其密码已过期,则在为此帐户重新指定一个新密码后,您可能会收到本文“症状”部分所描述的错误信息。

请按照下列步骤来验证应用程序池帐户所用的密码是否正确: a. 在 Internet 信息服务 (IIS) 管理器中,展开“应用程序池”。
b. 右键单击为虚拟服务器配置的应用程序池(例如,右键单击“MSSharePointPortalAppPool”),然后单击“属性”。
c. 单击“标识”选项卡。
d. 在“密码”框中,键入列在“用户名”框中的应用程序池帐户所用的密码,然后单击“确定”。
e. 在“确认密码”对话框中,再次键入密码,然后单击“确定”。

3.验证应用程序池帐户是服务器上的 IIS_WPG 组和 STS_WPG 组的成员。

根据您的具体情况选用下列方法之一。 a. 在成员服务器上安装了 SharePoint Portal Server 的情况下: 1.单击“开始”,指向“管理工具”,然后单击“计算机管理”。
2.展开“本地用户和组”,然后展开“用户”。
3.右键单击虚拟服务器的应用程序池使用的帐户,然后单击“属性”。
4.单击“成员属于”选项卡。

验证 IIS_WPG 和 STS_WPG 是否都出现在“成员属于”列表中。如果其中之一没有列出或者两者均未列出,请根据具体情况将 IIS_WPG 组、STS_WPG 组或者这两个组添加到列表中。

b. 在域控制器上安装了 SharePoint Portal Server 的情况下: 1.启动“Active Directory 用户和计算机”。
2.展开“用户”。
3.右键单击虚拟服务器的应用程序池使用的帐户,然后单击“属性”。
4.单击“成员属于”选项卡。

验证 IIS_WPG 和 STS_WPG 都出现在“成员属于”列表中。如果其中之一没有列出或者两者均未列出,请根据具体情况将 IIS_WPG 组、STS_WPG 组或者这两个组添加到列表中。


4.重新启动 IIS 以回收应用程序池: a. 在 Internet 信息服务 (IIS) 管理器中,右键单击“ServerName”,指向“所有任务”,然后单击“重新启动 IIS”。
b. 单击“在 ServerName 上重新启动 Internet 信息服务”,然后单击“确定”。

2007年5月16日星期三

文本分类子模块项目开发心得

1 第一次遇到MySQL数据库的BUG,晕翻>_<,害得我调试半天,原来是MYSQL把中文的“读”和“多”当成相同的字符串了,真是烂货数据库。。。
2 后来才搞清楚,是MySQl的字符编码设置的问题,搞了一上午和一下午,发现要改:
(1在my.ini处的2处都要改为default character set,
(2建的所有的表都要在最后加上default charset = gbk,
(3 string useGBK = "set names gbk";//成功调试必备的
DBComm = new MySQLCommand(useGBK, DBConn);
DBComm.ExecuteNonQuery();
3 一些常用的MySQLConnection 的函数集
static void Main(string[] args)
{
string sqlstr = "select * from manavatar";
MySQLConnection DBConn = new MySQLConnection(new MySQLConnectionString("192.168.0.13", "flashdata", "root", "root", 3306).AsString);
DBConn.Open();
//MySQLDataAdapter myadap = new MySQLDataAdapter(sqlstr, conn);
MySQLCommand DBComm = new MySQLCommand(sqlstr,DBConn);
MySQLDataReader DBReader = DBComm.ExecuteReaderEx(); //DBComm.ExecuteReaderEx();
MySQLDataAdapter DTAdapter = new MySQLDataAdapter(sqlstr,DBConn);

DataSet myDataSet = new DataSet();
DTAdapter.Fill(myDataSet,"manavatar");


try
{
while (DBReader.Read())
{
//Console.WriteLine("11");
Console.WriteLine("DBReader:{0},\t\t\tddddd:{1},\t\t {2}",DBReader.GetString(0), DBReader.GetString(1),DBReader.GetString(3));
}
Console.WriteLine("0000");
}
catch (Exception e)
{
Console.WriteLine("读入失败!"+e.ToString());
}
finally
{
Console.WriteLine("DBReader关闭");
Console.WriteLine("DBConn关闭");
DBReader.Close();
//DBConn.Close();
}

for (int i = 0; i < myDataSet.Tables["manavatar"].Rows.Count; i++)
{
Console.WriteLine("{0}",myDataSet.Tables["manavatar"].Rows[2]["user"]);
}


}

这是一个简单的例子。
在这里有个问题:dataset如果没设主键的话,可能会引起一些对数库操作的问题,比如会造成updata出现错误。

4 项目中导入了一个开源的DLL,MySQLDriverCS,他对C#调用MySQL做了很好的封装
5出现了诡异的语句INSERT INTO dic VALUES('/|\','军事20',9,1,0.181818181818182);
主要'/|\'是转义字符,暂时没有很好的解决方法

5 如果要调用generic 的Sort方法,必须实现CompareTo接口。这个接口有一个叫CompareTo(object)方法,如果“this”大于、小于 ...
如果想使用Array等的Find方法,必须重载Equals()方法,因为任何类都是继承Object类的。

6 无法显示 XML 页。
使用 XSL 样式表无法查看 XML 输入。请更正错误然后单击 刷新按钮,或以后重试。
--------------------------------------------------------------------------------
名称以无效字符开头。处理资源 'http://localhost/Asp.net/Default.aspx' 时出错。第 1 行,位置: 2
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
===================

解决办法:运行vs2005命令行(开始、所有程序、vs2005、tools,写得不准确),之后找到.net2.0的路径,我的是在C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727,之后运行aspnet_regiis.exe /i,就ok了。

(待续)

2007年5月14日星期一

MySQL常用命令(ZZ)

MySQL常用命令

建立库:
create database sss

使用库:
use sss

显示库:
show databases

删除库:
drop database sss

建立表:
create table object (obj_id numeric(10),obj_ra numeric(8,5),obj_de numeric(8,5),obj_mag numeric(4,2))

显示表:
show tables

显示表的结构:
describe object

删除表:
drop table object

授权外部连接:
grant all on sss.object to sss@192.168.1.12 identified by 'mysql'




# casularm 发表于2006-04-06 14:59:00 IP: 218.104.71.*
MySQL常用操作

启动:
/etc/init.d/mysql start

关闭:
/usr/bin/mysqladmin -u root -p shutdown

登陆:
mysql -uroot -p




# casularm 发表于2006-08-13 21:13:00 IP: 211.162.10.*
从外部文件向表中批量导入数据
load data infile 'e:/Data/minifiber.csv' into table minifiber fields terminated by ',';



# casularm 发表于2006-08-30 11:16:00 IP: 211.162.6.*
1.备份服务器数据:

mysqldump -h服务器IP地址 -u用户名 -p密码 --opt 数据库名>备份数据库名

例如:

mysqldump -h 192.168.1.100 -u sss -p --opt sss >sss_backup.sql

这条命令将服务器192.168.1.100上的sss这个数据库备份到本地计算机当前目录的sss_backup.sql这个文件中,这样,当数据库不小心损坏或数据丢失时,就可以由sss_backup.sql这个备份文件恢复了

2. 导入.sql数据到mysql数据库

mysql -h服务器IP地址 -u用户名 -p密码 -f -D 数据库名
备份文件名

例如:

mysql -h 192.168.1.100 -u sss -p -f -D sss 这条命令会将sss_backup.sql这个文件中的数据重新恢复到服务器sss数据库中。

3.注意事项
如果是新安装的数据库,需要新建个sss库
create database sss
备份和导入都要有sss数据库的权限
grant all on sss.* to sss@192.168.1.100 identified by 'mysql'




# casularm 发表于2006-10-29 17:06:00 IP: 211.162.10.*
使用PowerDesigner设计建造MySQL数据库

一、使用PowerDesigner制作建库脚本
1、设计CDM(Conceptual Data Model)
2、选择 Tools -> Generate Physical Data Model ,选择对应的DBMS为MySQL,生成PDM
3、选择 Database -> Generate Database ,在弹出的 Database Generation 对话框中选择脚本存取路径及脚本文件名称
4、点击确定后生成数据库建库脚本(*.sql)

二、使用建库脚本建立数据库
1、登陆 mysql -u root -p
2、建立空的databse create databse sss;
3、建立用户 grant all on sss.* to sss@192.168.1.100 identified by 'mysql';
4、退出 exit;
5、在终端中输入 mysql -h 192.168.1.100 -u sss -p < Script.sql
6、回车后输入密码即可

修改某个表的字段类型及指定为空或非空
>alter table 表名称 change 字段名称 字段名称 字段类型 [是否允许非空];
>alter table 表名称 modify 字段名称 字段类型 [是否允许非空];

修改某个表的字段名称及指定为空或非空
>alter table 表名称 change 字段原名称 字段新名称 字段类型 [是否允许非空];

例如:
修改表expert_info中的字段birth,允许其为空
>alter table expert_info change birth birth varchar(20) null;
mysql> ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20);
添加新字段 d:
mysql> ALTER TABLE t2 ADD d TIMESTAMP;
在a d 上增加索引:
mysql> ALTER TABLE t2 ADD INDEX (d), ADD INDEX (a);
删除字段c:
mysql> ALTER TABLE t2 DROP COLUMN c;
添加一个自动增长的字段c ,并且添加c 为主健:
mysql> ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> ADD PRIMARY KEY (c);

2007年5月13日星期日

Equals() 和运算符 == 的重载准则(C# 编程指南) ZZ

C# 程序员参考
Equals() 和运算符 == 的重载准则(C# 编程指南)

C# 中有两种不同的相等:引用相等和值相等。值相等是大家普遍理解的意义上的相等:它意味着两个对象包含相同的值。例如,两个值为 2 的整数具有值相等性。引用相等意味着要比较的不是两个对象,而是两个对象引用,这两个对象引用引用的是同一个对象。这可以通过简单的赋值来实现,如下面的示例所示:

C# 复制代码
System.Object a = new System.Object();
System.Object b = a;
System.Object.ReferenceEquals(a, b); //returns true

在上面的代码中,只存在一个对象,但存在对该对象的多个引用:a 和 b。由于它们引用的是同一个对象,因此具有引用相等性。如果两个对象具有引用相等性,则它们也具有值相等性,但是值相等性不能保证引用相等性。

若要检查引用相等性,应使用 ReferenceEquals。若要检查值相等性,应使用 Equals 或 Equals。

重写 Equals

Equals 是一个虚方法,允许任何类重写其实现。表示某个值(本质上可以是任何值类型)或一组值(如复数类)的任何类都应该重写 Equals。如果类型要实现 IComparable,则它应该重写 Equals。

Equals 的新实现应该遵循 Equals 的所有保证:

x.Equals(x) 返回 true。

x.Equals(y) 与 y.Equals(x) 返回相同的值。

如果 (x.Equals(y) && y.Equals(z)) 返回 true,则 x.Equals(z) 返回 true。

只要不修改 x 和 y 所引用的对象,x.Equals(y) 的后续调用就返回相同的值。

x.Equals(null) 返回 false。

Equals 的新实现不应该引发异常。建议重写 Equals 的任何类同时也重写 System.Object.GetHashCode。除了实现 Equals(对象)外,还建议所有的类为自己的类型实现 Equals(类型)以增强性能。例如:

C# 复制代码
class TwoDPoint : System.Object
{
public readonly int x, y;

public TwoDPoint(int x, int y) //constructor
{
this.x = x;
this.y = y;
}

public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}

// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}

// Return true if the fields match:
return (x == p.x) && (y == p.y);
}

public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}

// Return true if the fields match:
return (x == p.x) && (y == p.y);
}

public override int GetHashCode()
{
return x ^ y;
}
}

可调用基类的 Equals 的任何派生类在完成其比较之前都应该这样做。在下面的示例中,Equals 调用基类 Equals,后者将检查空参数并将参数的类型与派生类的类型做比较。这样就把检查派生类中声明的新数据字段的任务留给了派生类中的 Equals 实现:

C# 复制代码
class ThreeDPoint : TwoDPoint
{
public readonly int z;

public ThreeDPoint(int x, int y, int z)
: base(x, y)
{
this.z = z;
}

public override bool Equals(System.Object obj)
{
// If parameter cannot be cast to ThreeDPoint return false:
ThreeDPoint p = obj as ThreeDPoint;
if ((object)p == null)
{
return false;
}

// Return true if the fields match:
return base.Equals(obj) && z == p.z;
}

public bool Equals(ThreeDPoint p)
{
// Return true if the fields match:
return base.Equals((TwoDPoint)p) && z == p.z;
}

public override int GetHashCode()
{
return base.GetHashCode() ^ z;
}
}

2007年5月12日星期六

近期程序设计竞赛和公司面试的总结

1 树型DP的问题:


2 C++中讲string 快速转化到Int的问题:
stringstream是用于C++风格的字符串的输入输出的。
stringstream的构造函数原形如下: stringstream::stringstream(string str); #include

string s;
int a;
istringstream ss(s);
ss>>a;



3 C++中常用的字符串初始化函数
void *memset(void *s, int c, size_t n); Sets n bytes of a block of memory to byte c. memset sets the first n bytes of the array s to the character c.
用这个东东可以快速将字符串初始化.


4数学问题(发现好久没看数学了,连一些基本的东东都忘了)
递归方程组解的渐进阶的求法——差分方程法
这里只考虑形如:
T(n)=c1T(n-1)+c2T(n-2)+…+ ckT(n-k)+f(n),n≥k (6.18)
的递归方程。其中ci (i=l,2,…,k)为实常数,且ck≠0。它可改写为一个线性常系数k阶非齐次的差分方程:
T(n)-c1T(n-1)- c2T(n-2)-…-ckT(n-k)=f(n),n≥k (6.19)
(6.19)与线性常系数k阶非齐次常微分方程的结构十分相似,因而解法类同。限于篇幅,这里直接给出(6.19)的解法,略去其正确性的证明。
第一步,求(6.19)所对应的齐次方程:
T(n)-c1T(n-1)- c2T(n-2)-…-ckT(n-k)=0 (6.20)
的基本解系:写出(6.20)的特征方程:
C(t)=tk-c1tk-1-c2tk-2 -…-ck=0 (6.21)
若t=r是(6.21)的m重实根,则得(6.20)的m个基础解rn,nrn,n2rn,…,nm-1rn;若ρeiθ和ρe-iθ是(6.21)的一对l重的共扼复根,则得(6.20)的2l个基础解ρncosnθ,ρnsinnθ,nρncosnθ,nρnsinnθ,…,nl-1ρncosnθ,nl-1ρncosnθ。如此,求出(6.21)的所有的根,就可以得到(6.20)的k个的基础解。而且,这k个基础解构成了(6.20)的基础解系。即(6.20)的任意一个解都可以表示成这k个基础解的线性组合。
第二步,求(6.19)的一个特解。理论上,(6.19)的特解可以用Lagrange常数变易法得到。但其中要用到(6.20)的通解的显式表达,即(6.20)的基础解系的线性组合,十分麻烦。因此在实际中,常常采用试探法,也就是根据f(n)的特点推测特解的形式,留下若干可调的常数,将推测解代人(6.19)后确定。由于(6.19)的特殊性,可以利用迭加原理,将f(n)线性分解为若干个单项之和并求出各单项相应的特解,然后迭加便得到f(n)相应的特解。这使得试探法更为有效。为了方便,这里对三种特殊形式的f(n),给出(6.19)的相应特解并列在表6-1中,可供直接套用。其中pi,i=1,2,…,s是待定常数

2007年5月7日星期一

在 C# 中通过 P/Invoke 调用Win32 DLL(ZZ)

下载本文的代码: NET0307.exe (133KB)
我在自己最近的编程中注意到一个趋势,正是这个趋势才引出本月的专栏主题。最近,我在基于 Microsoft® .NET Framework 的应用程序中完成了大量的 Win32® Interop。我并不是要说我的应用程序充满了自定义的 interop 代码,但有时我会在 .NET Framework 类库中碰到一些次要但又繁絮、不充分的内容,通过调用该 Windows® API,可以快速减少这样的麻烦。
因此我认为,.NET Framework 1.0 或 1.1 版类库中存在任何 Windows 所没有的功能限制都不足为怪。毕竟,32 位的 Windows(不管何种版本)是一个成熟的操作系统,为广大客户服务了十多年。相比之下,.NET Framework 却是一个新事物。
随着越来越多的开发人员将生产应用程序转到托管代码,开发人员更频繁地研究底层操作系统以图找出一些关键功能显得很自然 — 至少目前是如此。
值得庆幸的是,公共语言运行库 (CLR) 的 interop 功能(称为平台调用 (P/Invoke))非常完善。在本专栏中,我将重点介绍如何实际使用 P/Invoke 来调用 Windows API 函数。当指 CLR 的 COM Interop 功能时,P/Invoke 当作名词使用;当指该功能的使用时,则将其当作动词使用。我并不打算直接介绍 COM Interop,因为它比 P/Invoke 具有更好的可访问性,却更加复杂,这有点自相矛盾,这使得将 COM Interop 作为专栏主题来讨论不太简明扼要。
走进 P/Invoke
首先从考察一个简单的 P/Invoke 示例开始。让我们看一看如何调用 Win32 MessageBeep 函数,它的非托管声明如以下代码所示:
BOOL MessageBeep( UINT uType // beep type);
为了调用 MessageBeep,您需要在 C# 中将以下代码添加到一个类或结构定义中:
[DllImport("User32.dll")]static extern Boolean MessageBeep(UInt32 beepType);
令人惊讶的是,只需要这段代码就可以使托管代码调用非托管的 MessageBeep API。它不是一个方法调用,而是一个外部方法定义。(另外,它接近于一个来自 C 而 C# 允许的直接端口,因此以它为起点来介绍一些概念是有帮助的。)来自托管代码的可能调用如下所示:
MessageBeep(0);
请注意,现在 MessageBeep 方法被声明为 static。这是 P/Invoke 方法所要求的,因为在该 Windows API 中没有一致的实例概念。接下来,还要注意该方法被标记为 extern。这是提示编译器该方法是通过一个从 DLL 导出的函数实现的,因此不需要提供方法体。
说到缺少方法体,您是否注意到 MessageBeep 声明并没有包含一个方法体?与大多数算法由中间语言 (IL) 指令组成的托管方法不同,P/Invoke 方法只是元数据,实时 (JIT) 编译器在运行时通过它将托管代码与非托管的 DLL 函数连接起来。执行这种到非托管世界的连接所需的一个重要信息就是导出非托管方法的 DLL 的名称。这一信息是由 MessageBeep 方法声明之前的 DllImport 自定义属性提供的。在本例中,可以看到,MessageBeep 非托管 API 是由 Windows 中的 User32.dll 导出的。
到现在为止,关于调用 MessageBeep 就剩两个话题没有介绍,请回顾一下,调用的代码与以下所示代码片段非常相似:
[DllImport("User32.dll")]static extern Boolean MessageBeep(UInt32 beepType);
最后这两个话题是与数据封送处理 (data marshaling) 和从托管代码到非托管函数的实际方法调用有关的话题。调用非托管 MessageBeep 函数可以由找到作用域内的extern MessageBeep 声明的任何托管代码执行。该调用类似于任何其他对静态方法的调用。它与其他任何托管方法调用的共同之处在于带来了数据封送处理的需要。
C# 的规则之一是它的调用语法只能访问 CLR 数据类型,例如 System.UInt32 和 System.Boolean。C# 显然不识别 Windows API 中使用的基于 C 的数据类型(例如 UINT 和 BOOL),这些类型只是 C 语言类型的类型定义而已。所以当 Windows API 函数 MessageBeep 按以下方式编写时
BOOL MessageBeep( UINT uType )
外部方法就必须使用 CLR 类型来定义,如您在前面的代码片段中所看到的。需要使用与基础 API 函数类型不同但与之兼容的 CLR 类型是 P/Invoke 较难使用的一个方面。因此,在本专栏的后面我将用完整的章节来介绍数据封送处理。
样式
在 C# 中对 Windows API 进行 P/Invoke 调用是很简单的。但如果类库拒绝使您的应用程序发出嘟声,应该想方设法调用 Windows 使它进行这项工作,是吗?
是的。但是与选择的方法有关,而且关系甚大!通常,如果类库提供某种途径来实现您的意图,则最好使用 API 而不要直接调用非托管代码,因为 CLR 类型和 Win32 之间在样式上有很大的不同。我可以将关于这个问题的建议归结为一句话。当您进行 P/Invoke 时,不要使应用程序逻辑直接属于任何外部方法或其中的构件。如果您遵循这个小规则,从长远看经常会省去许多的麻烦。
图 1 中的代码显示了我所讨论的 MessageBeep 外部方法的最少附加代码。图 1 中并没有任何显著的变化,而只是对无包装的外部方法进行一些普通的改进,这可以使工作更加轻松一些。从顶部开始,您会注意到一个名为 Sound 的完整类型,它专用于 MessageBeep。如果我需要使用 Windows API 函数 PlaySound 来添加对播放波形的支持,则可以重用 Sound 类型。然而,我不会因公开单个公共静态方法的类型而生气。毕竟这只是应用程序代码而已。还应该注意到,Sound 是密封的,并定义了一个空的私有构造函数。这些只是一些细节,目的是使用户不会错误地从 Sound 派生类或者创建它的实例。
图 1 中的代码的下一个特征是,P/Invoke 出现位置的实际外部方法是 Sound 的私有方法。这个方法只是由公共 MessageBeep 方法间接公开,后者接受 BeepTypes 类型的参数。这个间接的额外层是一个很关键的细节,它提供了以下好处。首先,应该在类库中引入一个未来的 beep 托管方法,可以重复地通过公共 MessageBeep 方法来使用托管 API,而不必更改应用程序中的其余代码。
该包装方法的第二个好处是:当您进行 P/Invoke 调用时,您放弃了免受访问冲突和其他低级破坏的权利,这通常是由 CLR 提供的。缓冲方法可以保护您的应用程序的其余部分免受访问冲突及类似问题的影响(即使它不做任何事而只是传递参数)。该缓冲方法将由 P/Invoke 调用引入的任何潜在的错误本地化。
将私有外部方法隐藏在公共包装后面的第三同时也是最后的一个好处是,提供了向该方法添加一些最小的 CLR 样式的机会。例如,在图 1 中,我将 Windows API 函数返回的 Boolean 失败转换成更像 CLR 的异常。我还定义了一个名为 BeepTypes 的枚举类型,它的成员对应于同该 Windows API 一起使用的定义值。由于 C# 不支持定义,因此可以使用托管枚举类型来避免幻数向整个应用程序代码扩散。
包装方法的最后一个好处对于简单的 Windows API 函数(如 MessageBeep)诚然是微不足道的。但是当您开始调用更复杂的非托管函数时,您会发现,手动将 Windows API 样式转换成对 CLR 更加友好的方法所带来的好处会越来越多。越是打算在整个应用程序中重用 interop 功能,越是应该认真地考虑包装的设计。同时我认为,在非面向对象的静态包装方法中使用对 CLR 友好的参数也并非不可以。
DLL Import 属性
现在是更深入地进行探讨的时候了。在对托管代码进行 P/Invoke 调用时,DllImportAttribute 类型扮演着重要的角色。DllImportAttribute 的主要作用是给 CLR 指示哪个 DLL 导出您想要调用的函数。相关 DLL 的名称被作为一个构造函数参数传递给 DllImportAttribute。
如果您无法肯定哪个 DLL 定义了您要使用的 Windows API 函数,Platform SDK 文档将为您提供最好的帮助资源。在 Windows API 函数主题文字临近结尾的位置,SDK 文档指定了 C 应用程序要使用该函数必须链接的 .lib 文件。在几乎所有的情况下,该 .lib 文件具有与定义该函数的系统 DLL 文件相同的名称。例如,如果该函数需要 C 应用程序链接到 Kernel32.lib,则该函数就定义在 Kernel32.dll 中。您可以在 MessageBeep 中找到有关 MessageBeep 的 Platform SDK 文档主题。在该主题结尾处,您会注意到它指出库文件是 User32.lib;这表明 MessageBeep 是从 User32.dll 中导出的。
可选的 DllImportAttribute 属性
除了指出宿主 DLL 外,DllImportAttribute 还包含了一些可选属性,其中四个特别有趣:EntryPoint、CharSet、SetLastError 和 CallingConvention。
EntryPoint 在不希望外部托管方法具有与 DLL 导出相同的名称的情况下,可以设置该属性来指示导出的 DLL 函数的入口点名称。当您定义两个调用相同非托管函数的外部方法时,这特别有用。另外,在 Windows 中还可以通过它们的序号值绑定到导出的 DLL 函数。如果您需要这样做,则诸如“#1”或“#129”的 EntryPoint 值指示 DLL 中非托管函数的序号值而不是函数名。
CharSet 对于字符集,并非所有版本的 Windows 都是同样创建的。Windows 9x 系列产品缺少重要的 Unicode 支持,而 Windows NT 和 Windows CE 系列则一开始就使用 Unicode。在这些操作系统上运行的 CLR 将Unicode 用于 String 和 Char 数据的内部表示。但也不必担心 — 当调用 Windows 9x API 函数时,CLR 会自动进行必要的转换,将其从 Unicode转换为 ANSI。
如果 DLL 函数不以任何方式处理文本,则可以忽略 DllImportAttribute 的 CharSet 属性。然而,当 Char 或 String 数据是等式的一部分时,应该将 CharSet 属性设置为 CharSet.Auto。这样可以使 CLR 根据宿主 OS 使用适当的字符集。如果没有显式地设置 CharSet 属性,则其默认值为 CharSet.Ansi。这个默认值是有缺点的,因为对于在 Windows 2000、Windows XP 和 Windows NT® 上进行的 interop 调用,它会消极地影响文本参数封送处理的性能。
应该显式地选择 CharSet.Ansi 或 CharSet.Unicode 的 CharSet 值而不是使用 CharSet.Auto 的唯一情况是:您显式地指定了一个导出函数,而该函数特定于这两种 Win32 OS 中的某一种。ReadDirectoryChangesW API 函数就是这样的一个例子,它只存在于基于 Windows NT 的操作系统中,并且只支持 Unicode;在这种情况下,您应该显式地使用 CharSet.Unicode。
有时,Windows API 是否有字符集关系并不明显。一种决不会有错的确认方法是在 Platform SDK 中检查该函数的 C 语言头文件。(如果您无法肯定要看哪个头文件,则可以查看 Platform SDK 文档中列出的每个 API 函数的头文件。)如果您发现该 API 函数确实定义为一个映射到以 A 或 W 结尾的函数名的宏,则字符集与您尝试调用的函数有关系。Windows API 函数的一个例子是在 WinUser.h 中声明的 GetMessage API,您也许会惊讶地发现它有 A 和 W 两种版本。
SetLastError 错误处理非常重要,但在编程时经常被遗忘。当您进行 P/Invoke 调用时,也会面临其他的挑战 — 处理托管代码中 Windows API 错误处理和异常之间的区别。我可以给您一点建议。
如果您正在使用 P/Invoke 调用 Windows API 函数,而对于该函数,您使用 GetLastError 来查找扩展的错误信息,则应该在外部方法的 DllImportAttribute 中将 SetLastError 属性设置为 true。这适用于大多数外部方法。
这会导致 CLR 在每次调用外部方法之后缓存由 API 函数设置的错误。然后,在包装方法中,可以通过调用类库的 System.Runtime.InteropServices.Marshal 类型中定义的 Marshal.GetLastWin32Error 方法来获取缓存的错误值。我的建议是检查这些期望来自 API 函数的错误值,并为这些值引发一个可感知的异常。对于其他所有失败情况(包括根本就没意料到的失败情况),则引发在 System.ComponentModel 命名空间中定义的 Win32Exception,并将 Marshal.GetLastWin32Error 返回的值传递给它。如果您回头看一下图 1 中的代码,您会看到我在 extern MessageBeep 方法的公共包装中就采用了这种方法。
CallingConvention 我将在此介绍的最后也可能是最不重要的一个 DllImportAttribute 属性是 CallingConvention。通过此属性,可以给 CLR 指示应该将哪种函数调用约定用于堆栈中的参数。CallingConvention.Winapi 的默认值是最好的选择,它在大多数情况下都可行。然而,如果该调用不起作用,则可以检查 Platform SDK 中的声明头文件,看看您调用的 API 函数是否是一个不符合调用约定标准的异常 API。
通常,本机函数(例如 Windows API 函数或 C- 运行时 DLL 函数)的调用约定描述了如何将参数推入线程堆栈或从线程堆栈中清除。大多数 Windows API 函数都是首先将函数的最后一个参数推入堆栈,然后由被调用的函数负责清理该堆栈。相反,许多 C-运行时 DLL 函数都被定义为按照方法参数在方法签名中出现的顺序将其推入堆栈,将堆栈清理工作交给调用者。
幸运的是,要让 P/Invoke 调用工作只需要让外围设备理解调用约定即可。通常,从默认值 CallingConvention.Winapi 开始是最好的选择。然后,在 C 运行时 DLL 函数和少数函数中,可能需要将约定更改为 CallingConvention.Cdecl。
数据封送处理
数据封送处理是 P/Invoke 具有挑战性的方面。当在托管和非托管代码之间传递数据时,CLR 遵循许多规则,很少有开发人员会经常遇到它们直至可将这些规则记住。除非您是一名类库开发人员,否则在通常情况下没有必要掌握其细节。为了最有效地在 CLR 上使用 P/Invoke,即使只偶尔需要 interop 的应用程序开发人员仍然应该理解数据封送处理的一些基础知识。
在本月专栏的剩余部分中,我将讨论简单数字和字符串数据的数据封送处理。我将从最基本的数字数据封送处理开始,然后介绍简单的指针封送处理和字符串封送处理。
封送数字和逻辑标量
Windows OS 大部分是用 C 编写的。因此,Windows API 所用到的数据类型要么是 C 类型,要么是通过类型定义或宏定义重新标记的 C 类型。让我们看看没有指针的数据封送处理。简单起见,首先重点讨论的是数字和布尔值。
当通过值向 Windows API 函数传递参数时,需要知道以下问题的答案:
• 数据从根本上讲是整型的还是浮点型的? • 如果数据是整型的,则它是有符号的还是无符号的? • 如果数据是整型的,则它的位数是多少? • 如果数据是浮点型的,则它是单精度的还是双精度的?
有时答案很明显,但有时却不明显。Windows API 以各种方式重新定义了基本的 C 数据类型。图 2 列出了 C 和 Win32 的一些公共数据类型及其规范,以及一个具有匹配规范的公共语言运行库类型。
通常,只要您选择一个其规范与该参数的 Win32 类型相匹配的 CLR 类型,您的代码就能够正常工作。不过也有一些特例。例如,在 Windows API 中定义的 BOOL 类型是一个有符号的 32 位整型。然而,BOOL 用于指示 Boolean 值 true 或 false。虽然您不用将 BOOL 参数作为 System.Int32 值封送,但是如果使用 System.Boolean 类型,就会获得更合适的映射。字符类型的映射类似于 BOOL,因为有一个特定的 CLR 类型 (System.Char) 指出字符的含义。
在了解这些信息之后,逐步介绍示例可能是有帮助的。依然采用 beep 主题作为例子,让我们来试一下 Kernel32.dll 低级 Beep,它会通过计算机的扬声器发生嘟声。这个方法的 Platform SDK 文档可以在 Beep 中找到。本机 API 按以下方式进行记录:
BOOL Beep( DWORD dwFreq, // Frequency DWORD dwDuration // Duration in milliseconds);
在参数封送处理方面,您的工作是了解什么 CLR 数据类型与 Beep API 函数所使用的 DWORD 和 BOOL 数据类型相兼容。回顾一下图 2 中的图表,您将看到 DWORD 是一个 32 位的无符号整数值,如同 CLR 类型 System.UInt32。这意味着您可以使用 UInt32 值作为送往 Beep 的两个参数。BOOL 返回值是一个非常有趣的情况,因为该图表告诉我们,在 Win32 中,BOOL 是一个 32 位的有符号整数。因此,您可以使用 System.Int32 值作为来自 Beep 的返回值。然而,CLR 也定义了 System.Boolean 类型作为 Boolean 值的语义,所以应该使用它来替代。CLR 默认将 System.Boolean 值封送为 32 位的有符号整数。此处所显示的外部方法定义是用于 Beep 的结果 P/Invoke 方法:
[DllImport("Kernel32.dll", SetLastError=true)]static extern Boolean Beep( UInt32 frequency, UInt32 duration);
指针参数
许多 Windows API 函数将指针作为它们的一个或多个参数。指针增加了封送数据的复杂性,因为它们增加了一个间接层。如果没有指针,您可以通过值在线程堆栈中传递数据。有了指针,则可以通过引用传递数据,方法是将该数据的内存地址推入线程堆栈中。然后,函数通过内存地址间接访问数据。使用托管代码表示此附加间接层的方式有多种。
在 C# 中,如果将方法参数定义为 ref 或 out,则数据通过引用而不是通过值传递。即使您没有使用 Interop 也是这样,但只是从一个托管方法调用到另一个托管方法。例如,如果通过 ref 传递 System.Int32 参数,则在线程堆栈中传递的是该数据的地址,而不是整数值本身。下面是一个定义为通过引用接收整数值的方法的示例:
void FlipInt32(ref Int32 num){ num = -num;}
这里,FlipInt32 方法获取一个 Int32 值的地址、访问数据、对它求反,然后将求反过的值赋给原始变量。在以下代码中,FlipInt32 方法会将调用程序的变量 x 的值从 10 更改为 -10:
Int32 x = 10;FlipInt32(ref x);
在托管代码中可以重用这种能力,将指针传递给非托管代码。例如,FileEncryptionStatus API 函数以 32 位无符号位掩码的形式返回文件加密状态。该 API 按以下所示方式进行记录:
BOOL FileEncryptionStatus( LPCTSTR lpFileName, // file name LPDWORD lpStatus // encryption status);
请注意,该函数并不使用它的返回值返回状态,而是返回一个 Boolean 值,指示调用是否成功。在成功的情况下,实际的状态值是通过第二个参数返回的。它的工作方式是调用程序向该函数传递指向一个 DWORD 变量的指针,而该 API 函数用状态值填充指向的内存位置。以下代码片段显示了一个调用非托管 FileEncryptionStatus 函数的可能外部方法定义:
[DllImport("Advapi32.dll", CharSet=CharSet.Auto)]static extern Boolean FileEncryptionStatus(String filename, out UInt32 status);
该定义使用 out 关键字来为 UInt32 状态值指示 by-ref 参数。这里我也可以选择 ref 关键字,实际上在运行时会产生相同的机器码。out 关键字只是一个 by-ref 参数的规范,它向 C# 编译器指示所传递的数据只在被调用的函数外部传递。相反,如果使用 ref 关键字,则编译器会假定数据可以在被调用的函数的内部和外部传递。
托管代码中 out 和 ref 参数的另一个很好的方面是,地址作为 by-ref 参数传递的变量可以是线程堆栈中的一个本地变量、一个类或结构的元素,也可以是具有合适数据类型的数组中的一个元素引用。调用程序的这种灵活性使得 by-ref 参数成为封送缓冲区指针以及单数值指针的一个很好的起点。只有在我发现 ref 或 out 参数不符合我的需要的情况下,我才会考虑将指针封送为更复杂的 CLR 类型(例如类或数组对象)。
如果您不熟悉 C 语法或者调用 Windows API 函数,有时很难知道一个方法参数是否需要指针。一个常见的指示符是看参数类型是否是以字母 P 或 LP 开头的,例如 LPDWORD 或 PINT。在这两个例子中,LP 和 P 指示参数是一个指针,而它们指向的数据类型分别为 DWORD 或 INT。然而,在有些情况下,可以直接使用 C 语言语法中的星号 (*) 将 API 函数定义为指针。以下代码片段展示了这方面的示例:
void TakesAPointer(DWORD* pNum);
可以看到,上述函数的唯一一个参数是指向 DWORD 变量的指针。
当通过 P/Invoke 封送指针时,ref 和 out 只用于托管代码中的值类型。当一个参数的 CLR 类型使用 struct 关键字定义时,可以认为该参数是一个值类型。Out 和 ref 用于封送指向这些数据类型的指针,因为通常值类型变量是对象或数据,而在托管代码中并没有对值类型的引用。相反,当封送引用类型对象时,并不需要 ref 和 out 关键字,因为变量已经是对象的引用了。
如果您对引用类型和值类型之间的差别不是很熟悉,请查阅 2000 年 12 月 发行的 MSDN® Magazine,在 .NET 专栏的主题中可以找到更多信息。大多数 CLR 类型都是引用类型;然而,除了 System.String 和 System.Object,所有的基元类型(例如 System.Int32 和 System.Boolean)都是值类型。
封送不透明 (Opaque) 指针:一种特殊情况
有时在 Windows API 中,方法传递或返回的指针是不透明的,这意味着该指针值从技术角度讲是一个指针,但代码却不直接使用它。相反,代码将该指针返回给 Windows 以便随后进行重用。
一个非常常见的例子就是句柄的概念。在 Windows 中,内部数据结构(从文件到屏幕上的按钮)在应用程序代码中都表示为句柄。句柄其实就是不透明的指针或有着指针宽度的数值,应用程序用它来表示内部的 OS 构造。
少数情况下,API 函数也将不透明指针定义为 PVOID 或 LPVOID 类型。在 Windows API 的定义中,这些类型意思就是说该指针没有类型。
当一个不透明指针返回给您的应用程序(或者您的应用程序期望得到一个不透明指针)时,您应该将参数或返回值封送为 CLR 中的一种特殊类型 — System.IntPtr。当您使用 IntPtr 类型时,通常不使用 out 或 ref 参数,因为 IntPtr 意为直接持有指针。不过,如果您将一个指针封送为一个指针,则对 IntPtr 使用 by-ref 参数是合适的。
在 CLR 类型系统中,System.IntPtr 类型有一个特殊的属性。不像系统中的其他基类型,IntPtr 并没有固定的大小。相反,它在运行时的大小是依底层操作系统的正常指针大小而定的。这意味着在 32 位的 Windows 中,IntPtr 变量的宽度是 32 位的,而在 64 位的 Windows 中,实时编译器编译的代码会将 IntPtr 值看作 64 位的值。当在托管代码和非托管代码之间封送不透明指针时,这种自动调节大小的特点十分有用。
请记住,任何返回或接受句柄的 API 函数其实操作的就是不透明指针。您的代码应该将 Windows 中的句柄封送成 System.IntPtr 值。
您可以在托管代码中将 IntPtr 值强制转换为 32 位或 64 位的整数值,或将后者强制转换为前者。然而,当使用 Windows API 函数时,因为指针应是不透明的,所以除了存储和传递给外部方法外,不能将它们另做它用。这种“只限存储和传递”规则的两个特例是当您需要向外部方法传递 null 指针值和需要比较 IntPtr 值与 null 值的情况。为了做到这一点,您不能将零强制转换为 System.IntPtr,而应该在 IntPtr 类型上使用 Int32.Zero 静态公共字段,以便获得用于比较或赋值的 null 值。
封送文本
在编程时经常要对文本数据进行处理。文本为 interop 制造了一些麻烦,这有两个原因。首先,底层操作系统可能使用 Unicode 来表示字符串,也可能使用 ANSI。在极少数情况下,例如 MultiByteToWideChar API 函数的两个参数在字符集上是不一致的。
第二个原因是,当需要进行 P/Invoke 时,要处理文本还需要特别了解到 C 和 CLR 处理文本的方式是不同的。在 C 中,字符串实际上只是一个字符值数组,通常以 null 作为结束符。大多数 Windows API 函数是按照以下条件处理字符串的:对于 ANSI,将其作为字符值数组;对于 Unicode,将其作为宽字符值数组。
幸运的是,CLR 被设计得相当灵活,当封送文本时问题得以轻松解决,而不用在意 Windows API 函数期望从您的应用程序得到的是什么。这里是一些需要记住的主要考虑事项:
• 是您的应用程序向 API 函数传递文本数据,还是 API 函数向您的应用程序返回字符串数据?或者二者兼有? • 您的外部方法应该使用什么托管类型? • API 函数期望得到的是什么格式的非托管字符串?
我们首先解答最后一个问题。大多数 Windows API 函数都带有 LPTSTR 或 LPCTSTR 值。(从函数角度看)它们分别是可修改和不可修改的缓冲区,包含以 null 结束的字符数组。“C”代表常数,意味着使用该参数信息不会传递到函数外部。LPTSTR 中的“T”表明该参数可以是 Unicode 或 ANSI,取决于您选择的字符集和底层操作系统的字符集。因为在 Windows API 中大多数字符串参数都是这两种类型之一,所以只要在 DllImportAttribute 中选择 CharSet.Auto,CLR 就按默认的方式工作。
然而,有些 API 函数或自定义的 DLL 函数采用不同的方式表示字符串。如果您要用到一个这样的函数,就可以采用 MarshalAsAttribute 修饰外部方法的字符串参数,并指明一种不同于默认 LPTSTR 的字符串格式。有关 MarshalAsAttribute 的更多信息,请参阅位于 MarshalAsAttribute Class 的 Platform SDK 文档主题。
现在让我们看一下字符串信息在您的代码和非托管函数之间传递的方向。有两种方式可以知道处理字符串时信息的传递方向。第一个也是最可靠的一个方法就是首先理解参数的用途。例如,您正调用一个参数,它的名称类似 CreateMutex 并带有一个字符串,则可以想像该字符串信息是从应用程序向 API 函数传递的。同时,如果您调用 GetUserName,则该函数的名称表明字符串信息是从该函数向您的应用程序传递的。
除了这种比较合理的方法外,第二种查找信息传递方向的方式就是查找 API 参数类型中的字母“C”。例如,GetUserName API 函数的第一个参数被定义为 LPTSTR 类型,它代表一个指向 Unicode 或 ANSI 字符串缓冲区的长指针。但是 CreateMutex 的名称参数被类型化为 LTCTSTR。请注意,这里的类型定义是一样的,但增加一个字母“C”来表明缓冲区为常数,API 函数不能写入。
一旦明确了文本参数是只用作输入还是用作输入/输出,就可以确定使用哪种 CLR 类型作为参数类型。这里有一些规则。如果字符串参数只用作输入,则使用 System.String 类型。在托管代码中,字符串是不变的,适合用于不会被本机 API 函数更改的缓冲区。
如果字符串参数可以用作输入和/或输出,则使用 System.StringBuilder 类型。StringBuilder 类型是一个很有用的类库类型,它可以帮助您有效地构建字符串,也正好可以将缓冲区传递给本机函数,由本机函数为您填充字符串数据。一旦函数调用返回,您只需要调用 StringBuilder 对象的 ToString 就可以得到一个 String 对象。
GetShortPathName API 函数能很好地用于显示什么时候使用 String、什么时候使用 StringBuilder,因为它只带有三个参数:一个输入字符串、一个输出字符串和一个指明输出缓冲区的字符长度的参数。
图 3 所示为加注释的非托管 GetShortPathName 函数文档,它同时指出了输入和输出字符串参数。它引出了托管的外部方法定义,也如图 3 所示。请注意第一个参数被封送为 System.String,因为它是一个只用作输入的参数。第二个参数代表一个输出缓冲区,它使用了 System.StringBuilder。
小结
本月专栏所介绍的 P/Invoke 功能足够调用 Windows 中的许多 API 函数。然而,如果您大量用到 interop,则会最终发现自己封送了很复杂的数据结构,甚至可能需要在托管代码中通过指针直接访问内存。实际上,本机代码中的 interop 可以是一个将细节和低级比特藏在里面的真正的潘多拉盒子。CLR、C# 和托管 C++ 提供了许多有用的功能;也许以后我会在本专栏介绍高级的 P/Invoke 话题。
同时,只要您觉得 .NET Framework 类库无法播放您的声音或者为您执行其他一些功能,您可以知道如何向原始而优秀的 Windows API 寻求一些帮助。
将您要发给 Jason 的问题和意见发送到 dot-net@microsoft.com
Jason Clark 为 Microsoft 和 Wintellect (http://www.wintellect.com) 提供培训和咨询,以前是 Windows NT 和 Windows 2000 Server 团队的开发人员。他与人合著了 Programming Server-side Applications for Microsoft Windows 2000 (Microsoft Press, 2000)。您可以通过 JClark@Wintellect.com 与 Jason 取得联系。

2007年4月4日星期三

谈谈Web Mining研究者掌握动态脚本语言的必要性发信站: 水木社区 (Fri Mar 23 17:58:30 2007),

站内自己平时很喜欢在闲暇时学习一些新的计算机语言,它使我对计算机的兴趣不至于在书写各种申报材料和论文中完全泯灭。特别是在我把工作平台转向Linux后,学习各种开源语言更成为自己掌握在Linux下工作的一种必然选择,除了C/C++、JAVA、C#这些主流开发语言外,我尤其对Perl、Python和Ruby这样的动态脚本语言情有独衷,这里特别谈谈自己在学习它们的过程中的一些体会。 第一次接触Perl语言是自己在作WebMining研究时从CMU大学的著名网页数据集Web-KB开始的,它的代码里有一些Perl语言脚本,往往几行代码就能完成JAVA这样的开发语言几十行代码才能完成的任务。显然它比Bash这样的Linux中的shell脚本功能要强大得多。由于第一次读到Perl语言书写的代码,感觉真的像天书一样难懂,特别是那些到处可见的$、@、%等奇怪的符号。为了完全弄懂Web-KB的这些代码,我下决心开始学习Perl,结果没想到从此一发不可收拾,很快就成为Perl铁定的忠实拥户。下面是我总结的几点它最突出的优点: 1。实用:它像编码世界里的"瑞士军刀",很多常用的处理方式特别作了很大的简化,让你用最少的代码量完成最多的功能。在JAVA语言里你需要首先声明各种变量,在程序执行前需要进行编译,在PERL语言里这些都去掉了,这大大简化了程序开发人员的开发效率。在JAVA程序里即使你只是打印一行"HelloWorld"也要先定义一个类,再定义一个static voidmain函数作为程序调用的入口,在PERL程序中这些全都不必了;再比如从网上下载网页在JAVA语言里至少要写上几行的代码,在Perl里只用一句就可以: use LWP::Simple; $html =get('http://www.sina.com.cn);由于经常需要引入package,所以选择use而不是JAVA里的import,因为它比后者少敲三个键。由于编程时90%的情况是处理文本,它就把正则表达式作为语言的内置功能而不像JAVA那样首先需要importre;在所有动态脚本语言中它也是运行速度最快的。2。第三方类库有集中的CPAN网站及其镜像站点统一管理:这是另一个让JAVA语言开发者嫉妒的优势,浏览一下网页http://search.cpan.org/吧,它把十年来所有开源的第三方软件包分门别类地集中存储,如果你愿意,也可以把自己开发的觉的有价值的软件包与全世界共享。JAVA虽然有Jarkata这样的第三方类库,但绝大多数还是需要我们自己去寻找。3。它是最像自然语言的计算机语言,不要忘记它的作者以前曾经是一个语言学家,如果你牢记这一点,那学习Perl语言便容易得多。我认为Perl语言也是目前我学到的所有语言中最具创新性的语言(它直接影响了Ruby),深深影响了以后各种新的语言的设计。4。它是完全开源的语言,它的作者是计算机历史上大名鼎鼎的LarryWall,他发明了patch命令和一个新闻组阅读器,但更主要的是他发明了Perl和CGI动态网页技术,他对Web的迅猛发展有直接的影响力。如果你想学习一门很多年后依然保持生命力的语言,那最保险的办法就是学习一门开源的语言,因为如果你去学习Delphi这样的商业语言,等到Borland公司一旦在商业市场上份额下降,那这种语言可能就完全风光不再。现在最热门的语言JAVA是Sun公司的宠儿,虽然Sun公司总裁声称在今年年底会完全公开JAVA源码,但显然这门语言的发展完全掌握在商业的运营模式中。Perl语言当然有它的缺点:不像Python和Ruby一样易学;面向对象功能不是一开始就设计而是后来添加的;代码可读性较差,过于灵活。LarryWall在2000年每年一度的开源大会上宣称开发新一代perl语言(即Perl6)的计划正式发始启动,它将摆脱现在向下兼容的包袱,从内核上对语言进行重新设计,采纳当下各门语言的精华同时保留它最根本的特性。这是让无数perl爱好者兴奋到整夜难眠的事情,现在开发Perl6还没有实现,这中间台湾的唐宗汉(现变性后改为唐凤)起了力挽狂澜的作用,是我们华人在开源领域最骄傲的人物。(见http://www.linuxeden.com/doc/21782.html)我认为学习像perl这样的脚本语言对计算机专业的研究者来说尤其适合,因为它可以大大加快开发原型或验证算法的过程,特别是它对文本处理的支持至今是无与伦比的。以我个人经验来说,作WebMining研究有一个很漂亮的想法很容易,但想得到实验数据的支持必须经过大量的Coding,它占用整个过程99%以上的时间(只关心发论文不在意伪造数据的除外)。如果用C++或JAVA语言来实现,你要花大量的时间用在Debug上面,但用Perl这样的快速开发语言,只花费十分之一的精力就能将其搞定,它免去了声明和编译(包括make过程),同时由于有很多现成的第三方软件包可以使用(在cpan里很容易找到Naive Bayes,Support VectorMachine这些机器学习工具),它的功能却一点也不逊色。特别的,由于它的代码量只有前者的几分甚至十几分之一,debug也相对容易得多。另外,使用perl语言最好结合Unix/Linux系统(虽然它在跨平台特性上一点不比JAVA差),这更能发挥它应有的作用。事实上在Linux系统下Perl是必备的工具(很多系统管理命令甚至带窗口的程序都是用它编写的,比如synaptic),你甚至无须去安装它。Python是另一个非常好的选择,它的好处是代码可读性好,对面向对象支持得非常好,非常易学(一个下午的时间可以学会80%场合用到的20%命令),另外与C/C++和Java的互相调用也作得非常出色(所以它是一种更好的gluelanguage),还有一个Perl语言没有的交互式编译器,它类似于以前苹果机上的Basic,你可以无须编写程序而直接在终端一行行边输入程序边看到结果,所以非常有利于快速开发。它的作者现在为Google工作,据说Google很多的代码都是用Python书写的。Python的名字来自国外非常流行的一个黑色幽默电影,放假时中央电影频道还专门介绍过它(下次我再次学习它时会先那部电影看一遍,找找感觉),开源世界的一大特色就是这种无比轻松的幽默而不是像微软产品包含的那种浓浓的商业气息。 Ruby现在由于Ruby onRails的流行而成为亲的上升之星,有人甚至预言它是未来的JAVA,它从Perl语言和Ada语言吸取了很多东西,自己打算有空闲时间的时候好好学习它。它的发明人是个日本人,有些中国程序员便排斥这门优秀的语言,我当然对此不会在意的。据说敏捷开发之父非常推崇这种语言,因为它是比JAVA还要纯的面向对象语言,像字符串和数学这些都作为对象处理,可以直接调用各种方

2007年3月29日星期四

Worker Threads in C#(http://www.codeproject.com/csharp/workerthread.asp)

Introduction


The .NET framework provides a lot of ways to implement multithreading
programs. I want to show how we can run a worker thread which makes syncronous
calls to a user interface (for example, a thread that reads a long recordset and
fills some control in the form).

To run thread I use:


  • Thread instance and main thread function

  • Two events used to stop thread. First event is set when main thread
    wants to stop worker thread; second event is set by worker thread when it really
    stops.

.NET allows you to call System.Windows.Forms.Control functions only from the thread in
which the control was created. To run them from another thread we need to use
the Control.Invoke (synchronous call) or Control.BeginInvoke (asynchronous call) functions. For tasks like
showing database records we need Invoke.

To implement this we will use:


  • A Delegate type for calling the form function. Delegate instance and
    function called using this delegate

  • The Invoke call from the worker thread.

The next problem is to stop the worker thread correctly. The steps to
do this are:


  • Set the event "Stop Thread"
  • Wait for the event "Thread is stopped"
  • Wait for the event process messages using the Application.DoEvents function. This prevents deadlocks because
    the worker thread makes Invoke calls which are processed in
    the main thread.

The thread function checks every iteration whether the "Stop Thread"
event has been set. If the event is set the function invokes clean-up
operations, sets the event "Thread is stopped" and returns.

Demo project has two classes: MainForm and LongProcess. The LongProcess.Run function
runs in a thread and fills the list box with some lines. The worker thread may
finish naturally or may be stopped when user presses the "Stop Thread" button or
closes the form.

Code fragments


Collapse
// MainForm.cs

namespace WorkerThread
{
// delegates used to call MainForm functions from worker thread
public delegate void DelegateAddString(String s);
public delegate void DelegateThreadFinished();

public class MainForm : System.Windows.Forms.Form
{
// ...

// worker thread
Thread m_WorkerThread;

// events used to stop worker thread
ManualResetEvent m_EventStopThread;
ManualResetEvent m_EventThreadStopped;

// Delegate instances used to call user interface functions
// from worker thread:
public DelegateAddString m_DelegateAddString;
public DelegateThreadFinished m_DelegateThreadFinished;

// ...

public MainForm()
{
InitializeComponent();

// initialize delegates
m_DelegateAddString = new DelegateAddString(this.AddString);
m_DelegateThreadFinished = new DelegateThreadFinished(this.ThreadFinished);

// initialize events
m_EventStopThread = new ManualResetEvent(false);
m_EventThreadStopped = new ManualResetEvent(false);

}

// ...

// Start thread button is pressed
private void btnStartThread_Click(object sender, System.EventArgs e)
{
// ...

// reset events
m_EventStopThread.Reset();
m_EventThreadStopped.Reset();

// create worker thread instance
m_WorkerThread = new Thread(new ThreadStart(this.WorkerThreadFunction));

m_WorkerThread.Name = "Worker Thread Sample"; // looks nice in Output window

m_WorkerThread.Start();

}


// Worker thread function.
// Called indirectly from btnStartThread_Click
private void WorkerThreadFunction()
{
LongProcess longProcess;

longProcess = new LongProcess(m_EventStopThread, m_EventThreadStopped, this);

longProcess.Run();
}

// Stop worker thread if it is running.
// Called when user presses Stop button or form is closed.
private void StopThread()
{
if ( m_WorkerThread != null && m_WorkerThread.IsAlive ) // thread is active
{
// set event "Stop"
m_EventStopThread.Set();

// wait when thread will stop or finish
while (m_WorkerThread.IsAlive)
{
// We cannot use here infinite wait because our thread
// makes syncronous calls to main form, this will cause deadlock.
// Instead of this we wait for event some appropriate time
// (and by the way give time to worker thread) and
// process events. These events may contain Invoke calls.
if ( WaitHandle.WaitAll(
(new ManualResetEvent[] {m_EventThreadStopped}),
100,
true) )
{
break;
}

Application.DoEvents();
}
}
}

// Add string to list box.
// Called from worker thread using delegate and Control.Invoke
private void AddString(String s)
{
listBox1.Items.Add(s);
}

// Set initial state of controls.
// Called from worker thread using delegate and Control.Invoke
private void ThreadFinished()
{
btnStartThread.Enabled = true;
btnStopThread.Enabled = false;
}

}
}

// LongProcess.cs

namespace WorkerThread
{
public class LongProcess
{
// ...

// Function runs in worker thread and emulates long process.
public void Run()
{
int i;
String s;

for (i = 1; i <= 10; i++)
  {                 // make step                 
  s = "Step number " + i.ToString() + " executed";                  
  Thread.Sleep(400);  // Make synchronous call to main form.    
             // MainForm.AddString function runs in main thread.  
               // (To make asynchronous call use BeginInvoke)   
              m_form.Invoke(m_form.m_DelegateAddString, new Object[] {s});                   // check if thread is cancelled             
      if ( m_EventStop.WaitOne(0, true) )               
    {                     // clean-up operations may be placed here                     // ...                      // inform main thread that this thread stopped                  
     m_EventStopped.Set();                 
       return;               
    }             
  } // Make synchronous call to main form             // to inform it that thread finished            
   m_form.Invoke(m_form.m_DelegateThreadFinished, null);         
 }     
 }
 }  

2007年3月6日星期二

用Visual C#调用Windows API函数(ZZ)

Api函数是构筑Windws应用程序的基石,每一种Windows应用程序开发工具,它提供的底层函数都间接或直接地调用了Windows API函数,同时为了实现功能扩展,一般也都提供了调用WindowsAPI函数的接口, 也就是说具备调用动态连接库的能力。Visual C#和其它开发工具一样也能够调用动态链接库的API函数。.NET框架本身提供了这样一种服务,允许受管辖的代码调用动态链接库中实现的非受管辖函数,包括操作系统提供的Windows API函数。它能够定位和调用输出函数,根据需要,组织其各个参数(整型、字符串类型、数组、和结构等等)跨越互操作边界。

下面以C#为例简单介绍调用API的基本过程:
动态链接库函数的声明
 动态链接库函数使用前必须声明,相对于VB,C#函数声明显得更加罗嗦,前者通过 Api Viewer粘贴以后,可以直接使用,而后者则需要对参数作些额外的变化工作。

 动态链接库函数声明部分一般由下列两部分组成,一是函数名或索引号,二是动态链接库的文件名。
  譬如,你想调用User32.DLL中的MessageBox函数,我们必须指明函数的名字MessageBoxA或MessageBoxW,以及库名字User32.dll,我们知道Win32 API对每一个涉及字符串和字符的函数一般都存在两个版本,单字节字符的ANSI版本和双字节字符的UNICODE版本。

 下面是一个调用API函数的例子:
[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
public static extern bool MoveFile(String src, String dst);

 其中入口点EntryPoint标识函数在动态链接库的入口位置,在一个受管辖的工程中,目标函数的原始名字和序号入口点不仅标识一个跨越互操作界限的函数。而且,你还可以把这个入口点映射为一个不同的名字,也就是对函数进行重命名。重命名可以给调用函数带来种种便利,通过重命名,一方面我们不用为函数的大小写伤透脑筋,同时它也可以保证与已有的命名规则保持一致,允许带有不同参数类型的函数共存,更重要的是它简化了对ANSI和Unicode版本的调用。CharSet用于标识函数调用所采用的是Unicode或是ANSI版本,ExactSpelling=false将告诉编译器,让编译器决定使用Unicode或者是Ansi版本。其它的参数请参考MSDN在线帮助.

 在C#中,你可以在EntryPoint域通过名字和序号声明一个动态链接库函数,如果在方法定义中使用的函数名与DLL入口点相同,你不需要在EntryPoint域显示声明函数。否则,你必须使用下列属性格式指示一个名字和序号。

[DllImport("dllname", EntryPoint="Functionname")]
[DllImport("dllname", EntryPoint="#123")]
值得注意的是,你必须在数字序号前加“#”
下面是一个用MsgBox替换MessageBox名字的例子:
[C#]
using System.Runtime.InteropServices;

public class Win32 {
[DllImport("user32.dll", EntryPoint="MessageBox")]
public static extern int MsgBox(int hWnd, String text, String caption, uint type);
}
许多受管辖的动态链接库函数期望你能够传递一个复杂的参数类型给函数,譬如一个用户定义的结构类型成员或者受管辖代码定义的一个类成员,这时你必须提供额外的信息格式化这个类型,以保持参数原有的布局和对齐。

C#提供了一个StructLayoutAttribute类,通过它你可以定义自己的格式化类型,在受管辖代码中,格式化类型是一个用StructLayoutAttribute说明的结构或类成员,通过它能够保证其内部成员预期的布局信息。布局的选项共有三种:

布局选项
描述
LayoutKind.Automatic
为了提高效率允许运行态对类型成员重新排序。
注意:永远不要使用这个选项来调用不受管辖的动态链接库函数。
LayoutKind.Explicit
对每个域按照FieldOffset属性对类型成员排序
LayoutKind.Sequential
对出现在受管辖类型定义地方的不受管辖内存中的类型成员进行排序。
传递结构成员
下面的例子说明如何在受管辖代码中定义一个点和矩形类型,并作为一个参数传递给User32.dll库中的PtInRect函数,
函数的不受管辖原型声明如下:
BOOL PtInRect(const RECT *lprc, POINT pt);
注意你必须通过引用传递Rect结构参数,因为函数需要一个Rect的结构指针。
[C#]
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}

[StructLayout(LayoutKind.Explicit]
public struct Rect {
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
}

class Win32API {
[DllImport("User32.dll")]
public static extern Bool PtInRect(ref Rect r, Point p);
}
类似你可以调用GetSystemInfo函数获得系统信息:
? using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO {
public uint dwOemId;
public uint dwPageSize;
public uint lpMinimumApplicationAddress;
public uint lpMaximumApplicationAddress;
public uint dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public uint dwProcessorLevel;
public uint dwProcessorRevision;
}




[DllImport("kernel32")]
static extern void GetSystemInfo(ref SYSTEM_INFO pSI);

SYSTEM_INFO pSI = new SYSTEM_INFO();
GetSystemInfo(ref pSI);

类成员的传递
同样只要类具有一个固定的类成员布局,你也可以传递一个类成员给一个不受管辖的动态链接库函数,下面的例子主要说明如何传递一个sequential顺序定义的MySystemTime类给User32.dll的GetSystemTime函数, 函数用C/C++调用规范如下:

void GetSystemTime(SYSTEMTIME* SystemTime);
不像传值类型,类总是通过引用传递参数.
[C#]
[StructLayout(LayoutKind.Sequential)]
public class MySystemTime {
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
class Win32API {
[DllImport("User32.dll")]
public static extern void GetSystemTime(MySystemTime st);
}
回调函数的传递:
从受管辖的代码中调用大多数动态链接库函数,你只需创建一个受管辖的函数定义,然后调用它即可,这个过程非常直接。
如果一个动态链接库函数需要一个函数指针作为参数,你还需要做以下几步:
首先,你必须参考有关这个函数的文档,确定这个函数是否需要一个回调;第二,你必须在受管辖代码中创建一个回调函数;最后,你可以把指向这个函数的指针作为一个参数创递给DLL函数,.

回调函数及其实现:
回调函数经常用在任务需要重复执行的场合,譬如用于枚举函数,譬如Win32 API 中的EnumFontFamilies(字体枚举), EnumPrinters(打印机), EnumWindows (窗口枚举)函数. 下面以窗口枚举为例,谈谈如何通过调用EnumWindow 函数遍历系统中存在的所有窗口

分下面几个步骤:
1. 在实现调用前先参考函数的声明
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARMAM IParam)
显然这个函数需要一个回调函数地址作为参数.
2. 创建一个受管辖的回调函数,这个例子声明为代表类型(delegate),也就是我们所说的回调,它带有两个参数hwnd和lparam,第一个参数是一个窗口句柄,第二个参数由应用程序定义,两个参数均为整形。

  当这个回调函数返回一个非零值时,标示执行成功,零则暗示失败,这个例子总是返回True值,以便持续枚举。
3. 最后创建以代表对象(delegate),并把它作为一个参数传递给EnumWindows 函数,平台会自动地 把代表转化成函数能够识别的回调格式。

[C#]
using System;
using System.Runtime.InteropServices;

public delegate bool CallBack(int hwnd, int lParam);

public class EnumReportApp {

[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);

public static void Main()
{
CallBack myCallBack = new CallBack(EnumReportApp.Report);
EnumWindows(myCallBack, 0);
}

public static bool Report(int hwnd, int lParam) {
Console.Write("窗口句柄为");
Console.WriteLine(hwnd);
return true;
}
}



指针类型参数传递:
 在Windows API函数调用时,大部分函数采用指针传递参数,对一个结构变量指针,我们除了使用上面的类和结构方法传递参数之外,我们有时还可以采用数组传递参数。

 下面这个函数通过调用GetUserName获得用户名
BOOL GetUserName(
LPTSTR lpBuffer, // 用户名缓冲区
LPDWORD nSize // 存放缓冲区大小的地址指针
);
 
[DllImport("Advapi32.dll",
EntryPoint="GetComputerName",
ExactSpelling=false,
SetLastError=true)]
static extern bool GetComputerName (
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
  [MarshalAs(UnmanagedType.LPArray)] Int32[] nSize );
 这个函数接受两个参数,char * 和int *,因为你必须分配一个字符串缓冲区以接受字符串指针,你可以使用String类代替这个参数类型,当然你还可以声明一个字节数组传递ANSI字符串,同样你也可以声明一个只有一个元素的长整型数组,使用数组名作为第二个参数。上面的函数可以调用如下:

byte[] str=new byte[20];
Int32[] len=new Int32[1];
len[0]=20;
GetComputerName (str,len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
 最后需要提醒的是,每一种方法使用前必须在文件头加上:
 using System.Runtime.InteropServices;