Search Results

Search found 37183 results on 1488 pages for 'string conversion'.

Page 111/1488 | < Previous Page | 107 108 109 110 111 112 113 114 115 116 117 118  | Next Page >

  • Marshalling non-Blittable Structs from C# to C++

    - by Greggo
    I'm in the process of rewriting an overengineered and unmaintainable chunk of my company's library code that interfaces between C# and C++. I've started looking into P/Invoke, but it seems like there's not much in the way of accessible help. We're passing a struct that contains various parameters and settings down to unmanaged codes, so we're defining identical structs. We don't need to change any of those parameters on the C++ side, but we do need to access them after the P/Invoked function has returned. My questions are: What is the best way to pass strings? Some are short (device id's which can be set by us), and some are file paths (which may contain Asian characters) Should I pass an IntPtr to the C# struct or should I just let the Marshaller take care of it by putting the struct type in the function signature? Should I be worried about any non-pointer datatypes like bools or enums (in other, related structs)? We have the treat warnings as errors flag set in C++ so we can't use the Microsoft extension for enums to force a datatype. Is P/Invoke actually the way to go? There was some Microsoft documentation about Implicit P/Invoke that said it was more type-safe and performant. For reference, here is one of the pairs of structs I've written so far: C++ /** Struct used for marshalling Scan parameters from managed to unmanaged code. */ struct ScanParameters { LPSTR deviceID; LPSTR spdClock; LPSTR spdStartTrigger; double spinRpm; double startRadius; double endRadius; double trackSpacing; UINT64 numTracks; UINT32 nominalSampleCount; double gainLimit; double sampleRate; double scanHeight; LPWSTR qmoPath; //includes filename LPWSTR qzpPath; //includes filename }; C# /// <summary> /// Struct used for marshalling scan parameters between managed and unmanaged code. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ScanParameters { [MarshalAs(UnmanagedType.LPStr)] public string deviceID; [MarshalAs(UnmanagedType.LPStr)] public string spdClock; [MarshalAs(UnmanagedType.LPStr)] public string spdStartTrigger; public Double spinRpm; public Double startRadius; public Double endRadius; public Double trackSpacing; public UInt64 numTracks; public UInt32 nominalSampleCount; public Double gainLimit; public Double sampleRate; public Double scanHeight; [MarshalAs(UnmanagedType.LPWStr)] public string qmoPath; [MarshalAs(UnmanagedType.LPWStr)] public string qzpPath; }

    Read the article

  • [C++] std::tring manipulation: whitespace, "newline escapes '\'" and comments #

    - by rubenvb
    Kind of looking for affirmation here. I have some hand-written code, which I'm not shy to say I'm proud of, which reads a file, removes leading whitespace, processes newline escapes '\' and removes comments starting with #. It also removes all empty lines (also whitespace-only ones). Any thoughts/recommendations? I could probably replace some std::cout's with std::runtime_errors... but that's not a priority here :) const int RecipeReader::readRecipe() { ifstream is_recipe(s_buffer.c_str()); if (!is_recipe) cout << "unable to open file" << endl; while (getline(is_recipe, s_buffer)) { // whitespace+comment removeLeadingWhitespace(s_buffer); processComment(s_buffer); // newline escapes + append all subsequent lines with '\' processNewlineEscapes(s_buffer, is_recipe); // store the real text line if (!s_buffer.empty()) v_s_recipe.push_back(s_buffer); s_buffer.clear(); } is_recipe.close(); return 0; } void RecipeReader::processNewlineEscapes(string &s_string, ifstream &is_stream) { string s_temp; size_t sz_index = s_string.find_first_of("\\"); while (sz_index <= s_string.length()) { if (getline(is_stream,s_temp)) { removeLeadingWhitespace(s_temp); processComment(s_temp); s_string = s_string.substr(0,sz_index-1) + " " + s_temp; } else cout << "Error: newline escape '\' found at EOF" << endl; sz_index = s_string.find_first_of("\\"); } } void RecipeReader::processComment(string &s_string) { size_t sz_index = s_string.find_first_of("#"); s_string = s_string.substr(0,sz_index); } void RecipeReader::removeLeadingWhitespace(string &s_string) { const size_t sz_length = s_string.size(); size_t sz_index = s_string.find_first_not_of(" \t"); if (sz_index <= sz_length) s_string = s_string.substr(sz_index); else if ((sz_index > sz_length) && (sz_length != 0)) // "empty" lines with only whitespace s_string.clear(); } Some extra info: std::string s_buffer is a class data member, so is std::vector v_s_recipe. Any comment is welcome :)

    Read the article

  • Java looping through array - Optimization

    - by oudouz
    I've got some Java code that runs quite the expected way, but it's taking some amount of time -some seconds- even if the job is just looping through an array. The input file is a Fasta file as shown in the image below. The file I'm using is 2.9Mo, and there are some other Fasta file that can take up to 20Mo. And in the code im trying to loop through it by bunches of threes, e.g: AGC TTT TCA ... etc The code has no functional sens for now but what I want is to append each Amino Acid to it's equivalent bunch of Bases. Example : AGC - Ser / CUG Leu / ... etc So what's wrong with the code ? and Is there any way to do it better ? Any optimization ? Looping through the whole String is taking some time, maybe just seconds, but need to find a better way to do it. import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class fasta { public static void main(String[] args) throws IOException { File fastaFile; FileReader fastaReader; BufferedReader fastaBuffer = null; StringBuilder fastaString = new StringBuilder(); try { fastaFile = new File("res/NC_017108.fna"); fastaReader = new FileReader(fastaFile); fastaBuffer = new BufferedReader(fastaReader); String fastaDescription = fastaBuffer.readLine(); String line = fastaBuffer.readLine(); while (line != null) { fastaString.append(line); line = fastaBuffer.readLine(); } System.out.println(fastaDescription); System.out.println(); String currentFastaAcid; for (int i = 0; i < fastaString.length(); i+=3) { currentFastaAcid = fastaString.toString().substring(i, i + 3); System.out.println(currentFastaAcid); } } catch (NullPointerException e) { System.out.println(e.getMessage()); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } finally { fastaBuffer.close(); } } }

    Read the article

  • Searching strings C

    - by Skittles
    First time posting here so I'm sorry if I mess up. I need to search a string and return any strings containing the search data with the search data highlighted. If my string is Hi my name is and I searched name it would produce Hi my NAME is This is a quick code I wrote that works but it only works once. If I try and search again it seg faults. I was hoping someone could hint me at a better way to write this because this code is disgusting! void search(char * srcStr, int n){ int cnt = 0, pnt,i = 0; char tmpText[500]; char tmpName[500]; char *ptr, *ptr2, *ptrLast; int num; while(*(node->text+cnt) != '\0'){ //finds length of string cnt++; } for(pnt = 0; pnt < cnt; pnt++){ //copies node->text into a tmp string tmpText[pnt] = *(node->text+pnt); } tmpText[pnt+1] = '\0'; //prints up to first occurrence of srcStr ptr = strcasestr(tmpText, srcStr); for(num = 0; num < ptr-tmpText; num++){ printf("%c",tmpText[num]); } //prints first occurrence of srcStr in capitals for(num = 0; num < n; num++){ printf("%c",toupper(tmpText[ptr-tmpText+num])); } ptr2 = strcasestr((ptr+n),srcStr); for(num = (ptr-tmpText+n); num < (ptr2-tmpText); num++){ printf("%c",tmpText[num]); } while((ptr = strcasestr((ptr+n), srcStr)) != NULL){ ptr2 = strcasestr((ptr+n),srcStr); for(num = (ptr-tmpText+n); num < (ptr2-tmpText); num++){ printf("%c",tmpText[num]); } for(num = 0; num < n; num++){ printf("%c",toupper(tmpText[ptr-tmpText+num])); } ptrLast = ptr; } //prints remaining string after last occurrence for(num = (ptrLast-tmpText+n); num < cnt; num++){ printf("%c",tmpText[num]); } }

    Read the article

  • Find files containing a string on the whole filesystem

    - by Fabio
    I need to find all the instances of a given string in the whole filesystem, because I don't remember in which configuration files, script or any other programs I put it and I need to update that string with a new one. I tried with the following command `grep -nr 'needle' / --exclude-dir=.svn | mail [email protected] -s 'References on xxx' If I run this command on a small directory it gives me the output I need in the form /path1/:nn:line containing needle /path2/:nn:line containing needle where /path1 is the full path of the file, nn is the row containing the needle and last field is the content of the line. However when I run the command on the root directory the grep process hang after a while. I run this script about 8 hours ago and even on a small filesystem (less than 5GB) it doesn't end and if I run top or ps the process seems sleeping root 24909 0.0 0.1 3772 1520 pts/1 S+ Feb10 0:15 grep -nr needle / --exclude-dir=.svn Why it doesn't end? Is there any better way to do this (it's a one time job, I don't need to execute this more than once) Thanks.

    Read the article

  • IIS Url Rewrite Capturing query string and escaping characters

    - by LiamB
    We are just adding some redirects for an old site to a new one in IIS7 using the URL Rewrite 'plugin'. The old site's URL are all based on the query string, we'd usually do explicit rewrites like below. But this wont work in the case of the query string. <rule name="Redirect-1" patternSyntax="Wildcard" stopProcessing="true"> <match url="index.php?option=m_content&view=article&id=15&Itemid=16" /> <action type="Redirect" url="http://newurl/some-page" /> </rule> So using the 2 URL's above how can we do a 301 redirect?

    Read the article

  • How to rename everything matching a certain string in a folder

    - by lostiniceland
    Hello Everyone I am running Linux and I have some basic console knowledge but my current problem is quite difficult and I dont know how to achieve this. I want/need to rename everything within a folder that matches a given string. By everything I mean folders/files content within a file content in hidden files Basically I want to refactor a Java-project. Sure, I could use Eclipse to handle the replacing, but this leaves out the folders or resources outside of my workspace. I was thinking of a script that could do the job for me but this seems rather tricky. For instance when it comes to folder-/file-rename I want to replace only the part of the name that matches my string, the rest should remain untouched. Maybe someone already has something like this in his/her script-collection :-) Thanks in advance Marc

    Read the article

  • How to rename everything matching a certain string in a folder

    - by lostiniceland
    Hello Everyone I am running Linux and I have some basic console knowledge but my current problem is quite difficult and I dont know how to achieve this. I want/need to rename everything within a folder that matches a given string. By everything I mean folders/files content within a file content in hidden files Basically I want to refactor a Java-project. Sure, I could use Eclipse to handle the replacing, but this leaves out the folders or resources outside of my workspace. I was thinking of a script that could do the job for me but this seems rather tricky. For instance when it comes to folder-/file-rename I want to replace only the part of the name that matches my string, the rest should remain untouched. Maybe someone already has something like this in his/her script-collection :-) Thanks in advance Marc

    Read the article

  • Criteria strings, how many different criteria can be entered to retrieve specific data?

    - by Janet
    For our membership database we are currently using an old DOS program "Arclist". The program is old but the one feature we desperately need in a database program is to be able to enter multiple criteria at one time for more of a "one time" extraction of the data meeting all the various criteria entered in what I call a "criteria string". An example may be extracting only those records with zip codes matching (67893, 54235, 54323, 54201, 54302, 54303, 54301, 67894, 67895). Another set of criteria might be to omit records, not equal to, one type of criteria in one field and also extract records matching criteria in another field. So we would want records "not equal to" in one field, but whose information equals requested information in another field.

    Read the article

  • Highlight identical strings in vi(m)

    - by Boldewyn
    One feature of Notepad++, which I find really useful and haven't found elsewhere, is the highlighting of other text that is identical to the one currently selected. Is there something similar possible with vi(m)? (Of course, there is. But how do I achieve it?) That is, any of those: If I am in Visual Mode and have text selected: Highlight identical text If I have searched /foo, highlight all instances of foo. If I am at the beginning of a string (series of characters, numbers or underscores), highlight all other matching strings (prefered solution). The last one is similar to the closing parentheses matching and IMHO the most useful. Edit: For my second use case, I found a solution (that is, Google found it...): :set hls However, the others remain.

    Read the article

  • Automatically send a string when opening a raw connection in putty

    - by MBraedley
    I have a program running on a server that accepts TCP/IP connections on a specified port. When a connection is made, this program waits for the user (i.e. me) to send a string which identifies the type of user. Once the user identifies themselves, the program will start sending data that is relevant to that user type. I want to automate the first step and have putty automatically send the user identification string once the connection is made. I've been through the settings, and can't seem to find anything like "send following commands on connection". Any help would be appreciated.

    Read the article

  • Command output as string

    - by rik
    I want to get output from command C:\Program Files (x86)\Java\jre7\bin\java.exe" -version as string variable. I tried this way: $out = &"C:\Program Files (x86)\Java\jre7\bin\java.exe" -version but it gives error message: java.exe : java version "1.7.0_05" At line:1 char:9 + $out = & <<<< "C:\Program Files (x86)\Java\jre7\bin\java.exe" -version + CategoryInfo : NotSpecified: (java version "1.7.0_05":String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Java(TM) SE Runtime Environment (build 1.7.0_05-b05) Java HotSpot(TM) Client VM (build 23.1-b03, mixed mode, sharing) $out variable seems empty. What am I doing wrong?

    Read the article

  • The Return Of __FILE__ And __LINE__ In .NET 4.5

    - by Alois Kraus
    Good things are hard to kill. One of the most useful predefined compiler macros in C/C++ were __FILE__ and __LINE__ which do expand to the compilation units file name and line number where this value is encountered by the compiler. After 4.5 versions of .NET we are on par with C/C++ again. It is of course not a simple compiler expandable macro it is an attribute but it does serve exactly the same purpose. Now we do get CallerLineNumberAttribute  == __LINE__ CallerFilePathAttribute        == __FILE__ CallerMemberNameAttribute  == __FUNCTION__ (MSVC Extension)   The most important one is CallerMemberNameAttribute which is very useful to implement the INotifyPropertyChanged interface without the need to hard code the name of the property anymore. Now you can simply decorate your change method with the new CallerMemberName attribute and you get the property name as string directly inserted by the C# compiler at compile time.   public string UserName { get { return _userName; } set { _userName=value; RaisePropertyChanged(); // no more RaisePropertyChanged(“UserName”)! } } protected void RaisePropertyChanged([CallerMemberName] string member = "") { var copy = PropertyChanged; if(copy != null) { copy(new PropertyChangedEventArgs(this, member)); } } Nice and handy. This was obviously the prime reason to implement this feature in the C# 5.0 compiler. You can repurpose this feature for tracing to get your hands on the method name of your caller along other stuff very fast now. All infos are added during compile time which is much faster than other approaches like walking the stack. The example on MSDN shows the usage of this attribute with an example public static void TraceMessage(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Console.WriteLine("Hi {0} {1} {2}({3})", message, memberName, sourceFilePath, sourceLineNumber); }   When I do think of tracing I do usually want to have a API which allows me to Trace method enter and leave Trace messages with a severity like Info, Warning, Error When I do print a trace message it is very useful to print out method and type name as well. So your API must either be able to pass the method and type name as strings or extract it automatically via walking back one Stackframe and fetch the infos from there. The first glaring deficiency is that there is no CallerTypeAttribute yet because the C# compiler team was not satisfied with its performance.   A usable Trace Api might therefore look like   enum TraceTypes { None = 0, EnterLeave = 1 << 0, Info = 1 << 1, Warn = 1 << 2, Error = 1 << 3 } class Tracer : IDisposable { string Type; string Method; public Tracer(string type, string method) { Type = type; Method = method; if (IsEnabled(TraceTypes.EnterLeave,Type, Method)) { } } private bool IsEnabled(TraceTypes traceTypes, string Type, string Method) { // Do checking here if tracing is enabled return false; } public void Info(string fmt, params object[] args) { } public void Warn(string fmt, params object[] args) { } public void Error(string fmt, params object[] args) { } public static void Info(string type, string method, string fmt, params object[] args) { } public static void Warn(string type, string method, string fmt, params object[] args) { } public static void Error(string type, string method, string fmt, params object[] args) { } public void Dispose() { // trace method leave } } This minimal trace API is very fast but hard to maintain since you need to pass in the type and method name as hard coded strings which can change from time to time. But now we have at least CallerMemberName to rid of the explicit method parameter right? Not really. Since any acceptable usable trace Api should have a method signature like Tracexxx(… string fmt, params [] object args) we not able to add additional optional parameters after the args array. If we would put it before the format string we would need to make it optional as well which would mean the compiler would need to figure out what our trace message and arguments are (not likely) or we would need to specify everything explicitly just like before . There are ways around this by providing a myriad of overloads which in the end are routed to the very same method but that is ugly. I am not sure if nobody inside MS agrees that the above API is reasonable to have or (more likely) that the whole talk about you can use this feature for diagnostic purposes was not a core feature at all but a simple byproduct of making the life of INotifyPropertyChanged implementers easier. A way around this would be to allow for variable argument arrays after the params keyword another set of optional arguments which are always filled by the compiler but I do not know if this is an easy one. The thing I am missing much more is the not provided CallerType attribute. But not in the way you would think of. In the API above I did add some filtering based on method and type to stay as fast as possible for types where tracing is not enabled at all. It should be no more expensive than an additional method call and a bool variable check if tracing for this type is enabled at all. The data is tightly bound to the calling type and method and should therefore become part of the static type instance. Since extending the CLR type system for tracing is not something I do expect to happen I have come up with an alternative approach which allows me basically to attach run time data to any existing type object in super fast way. The key to success is the usage of generics.   class Tracer<T> : IDisposable { string Method; public Tracer(string method) { if (TraceData<T>.Instance.Enabled.HasFlag(TraceTypes.EnterLeave)) { } } public void Dispose() { if (TraceData<T>.Instance.Enabled.HasFlag(TraceTypes.EnterLeave)) { } } public static void Info(string fmt, params object[] args) { } /// <summary> /// Every type gets its own instance with a fresh set of variables to describe the /// current filter status. /// </summary> /// <typeparam name="T"></typeparam> internal class TraceData<UsingType> { internal static TraceData<UsingType> Instance = new TraceData<UsingType>(); public bool IsInitialized = false; // flag if we need to reinit the trace data in case of reconfigured trace settings at runtime public TraceTypes Enabled = TraceTypes.None; // Enabled trace levels for this type } } We do not need to pass the type as string or Type object to the trace Api. Instead we define a generic Api that accepts the using type as generic parameter. Then we can create a TraceData static instance which is due to the nature of generics a fresh instance for every new type parameter. My tests on my home machine have shown that this approach is as fast as a simple bool flag check. If you have an application with many types using tracing you do not want to bring the app down by simply enabling tracing for one special rarely used type. The trace filter performance for the types which are not enabled must be therefore the fasted code path. This approach has the nice side effect that if you store the TraceData instances in one global list you can reconfigure tracing at runtime safely by simply setting the IsInitialized flag to false. A similar effect can be achieved with a global static Dictionary<Type,TraceData> object but big hash tables have random memory access semantics which is bad for cache locality and you always need to pay for the lookup which involves hash code generation, equality check and an indexed array access. The generic version is wicked fast and allows you to add more features to your tracing Api with minimal perf overhead. But it is cumbersome to write the generic type argument always explicitly and worse if you do refactor code and move parts of it to other classes it might be that you cannot configure tracing correctly. I would like therefore to decorate my type with an attribute [CallerType] class Tracer<T> : IDisposable to tell the compiler to fill in the generic type argument automatically. class Program { static void Main(string[] args) { using (var t = new Tracer()) // equivalent to new Tracer<Program>() { That would be really useful and super fast since you do not need to pass any type object around but you do have full type infos at hand. This change would be breaking if another non generic type exists in the same namespace where now the generic counterpart would be preferred. But this is an acceptable risk in my opinion since you can today already get conflicts if two generic types of the same name are defined in different namespaces. This would be only a variation of this issue. When you do think about this further you can add more features like to trace the exception in your Dispose method if the method is left with an exception with that little trick I did write some time ago. You can think of tracing as a super fast and configurable switch to write data to an output destination or to execute alternative actions. With such an infrastructure you can e.g. Reconfigure tracing at run time. Take a memory dump when a specific method is left with a specific exception. Throw an exception when a specific trace statement is hit (useful for testing error conditions). Execute a passed delegate which e.g. dumps additional state when enabled. Write data to an in memory ring buffer and dump it when specific events do occur (e.g. method is left with an exception, triggered from outside). Write data to an output device. …. This stuff is really useful to have when your code is in production on a mission critical server and you need to find the root cause of sporadic crashes of your application. It could be a buggy graphics card driver which throws access violations into your application (ok with .NET 4 not anymore except if you enable a compatibility flag) where you would like to have a minidump or you have reached after two weeks of operation a state where you need a full memory dump at a specific point in time in the middle of an transaction. At my older machine I do get with this super fast approach 50 million traces/s when tracing is disabled. When I do know that tracing is enabled for this type I can walk the stack by using StackFrameHelper.GetStackFramesInternal to check further if a specific action or output device is configured for this method which is about 2-3 times faster than the regular StackTrace class. Even with one String.Format I am down to 3 million traces/s so performance is not so important anymore since I do want to do something now. The CallerMemberName feature of the C# 5 compiler is nice but I would have preferred to get direct access to the MethodHandle and not to the stringified version of it. But I really would like to see a CallerType attribute implemented to fill in the generic type argument of the call site to augment the static CLR type data with run time data.

    Read the article

  • C++ 'using': Should I use it or should I avoid it?

    - by Mehrdad
    I realize there are subtly different semantics for some of these, because of ADL. In general, though: Which one should I prefer (if any), and why? (Or does it depend on the situation (e.g. inline header vs. implementation?) Also: should I prefer ::std:: over std::? using namespace std; pair<string::const_iterator, string::const_iterator> f(const string &s) { return make_pair(s.begin(), s.end()); } or std::pair<std::string::const_iterator, std::string::const_iterator> f(const std::string &s) { return std::make_pair(s.begin(), s.end()); } or using std::pair; using std::string; pair<string::const_iterator, string::const_iterator> f(const string &s) { return make_pair(s.begin(), s.end()); } or std::pair<std::string::const_iterator, std::string::const_iterator> f(const std::string &s) { using std::make_pair; return make_pair(s.begin(), s.end()); } or std::pair<std::string::const_iterator, std::string::const_iterator> f(const std::string &s) { using namespace std; return make_pair(s.begin(), s.end()); } or something else? (This is assuming I don't have C++11 and auto.)

    Read the article

  • What is Causing This Memory Leak in Delphi?

    - by lkessler
    I just can't figure out this memory leak that EurekaLog is reporting for my program. I'm using Delphi 2009. Here it is: Memory Leak: Type=Data; Total size=26; Count=1; The stack is: System.pas _UStrSetLength 17477 System.pas _UStrCat 17572 Process.pas InputGedcomFile 1145 That is all there is in the stack. EurekaLog is pointing me to the location where the memory that was not released was first allocated. According to it, the line in my program is line 1145 of InputGedcomFile. That line is: CurStruct0Key := 'HEAD' + Level0Key; where CurStruct0Key and Level0Key are simply defined in the procedure as local variables that should be dynamically handled by the Delphi memory manager when entering and leaving the procedure: var CurStruct0Key, Level0Key: string; So now I look at the _UStrCat procedure in the System Unit. Line 17572 is: CALL _UStrSetLength // Set length of Dest and I go to the _UStrSetLength procedure in the System Unit, and the relevant lines are: @@isUnicode: CMP [EAX-skew].StrRec.refCnt,1 // !!! MT safety JNE @@copyString // not unique, so copy SUB EAX,rOff // Offset EAX "S" to start of memory block ADD EDX,EDX // Double length to get size JO @@overflow ADD EDX,rOff+2 // Add string rec size JO @@overflow PUSH EAX // Put S on stack MOV EAX,ESP // to pass by reference CALL _ReallocMem POP EAX ADD EAX,rOff // Readjust MOV [EBX],EAX // Store MOV [EAX-skew].StrRec.length,ESI MOV WORD PTR [EAX+ESI*2],0 // Null terminate TEST EDI,EDI // Was a temp created? JZ @@exit PUSH EDI MOV EAX,ESP CALL _LStrClr POP EDI JMP @@exit where line 17477 is the "CALL _ReallocMem" line. So then what is the memory leak? Surely a simple concatenate of a string constant to a local string variable should not be causing a memory leak. Why is EurekaLog pointing me to the ReallocMem line in a _UStrSetLength routine that is part of Delphi? This is Delphi 2009 and I am using the new unicode strings. Any help or explanation here will be much appreciated.

    Read the article

  • Exchanging strings (PChar) between a Freepascal compiled DLL and a Delphi compiled EXE

    - by John Riche
    After a lot of experimentations, I found a way to exchange PChar from a FreePascal compiled DLL with a Delphi compiled EXE. I'm in charge of both the DLL and EXE source code but one MUST BE in FreePascal and the other one in Delphi. My solution involves the following methods in the DLL: function GetAString(): PChar; var aString: string; begin aString := 'My String'; result := StrAlloc(length(aString) + 1); StrPCopy(result, aString); end; procedure FreeString(aString: PChar); begin StrDispose(aString); end; And from the Delphi EXE, to call the GetAString method, I need to Call the GetAString method, save the PChar to an actual Delphi String and call the FreeString method. Is this the best way of exchanging a string from a FreePascal DLL with a Delphi EXE ? Can I avoid the call to FreeString from Delphi ? And finally, if that's the correct solution, how will it behave with Delphi 2010 and the WideString by default: do I need to force WidePChar in FreePascal too ?

    Read the article

  • How do I get 3 lines of text from a paragraph

    - by Keltex
    I'm trying to create an "snippet" from a paragraph. I have a long paragraph of text with a word hilighted in the middle. I want to get the line containing the word before that line and the line after that line. I have the following piece of information: The text (in a string) The lines are deliminated by a NEWLINE character \n I have the index into the string of the text I want to hilight A couple other criteria: If my word falls on first line of the paragraph, it should show the 1st 3 lines If my word falls on the last line of the paragraph, it should show the last 3 lines Should show the entire paragraph in the degenative cases (the paragraph only has 1 or 2 lines) Here's an example: This is the 1st line of CAT text in the paragraph This is the 2nd line of BIRD text in the paragraph This is the 3rd line of MOUSE text in the paragraph This is the 4th line of DOG text in the paragraph This is the 5th line of RABBIT text in the paragraph Example, if my index points to BIRD, it should show lines 1, 2, & 3 as one complete string like this: This is the 1st line of CAT text in the paragraph This is the 2nd line of BIRD text in the paragraph This is the 3rd line of MOUSE text in the paragraph If my index points to DOG, it should show lines 3, 4, & 5 as one complete string like this: This is the 3rd line of MOUSE text in the paragraph This is the 4th line of DOG text in the paragraph This is the 5th line of RABBIT text in the paragraph etc. Anybody want to help tackle this?

    Read the article

  • AutoCompleteExtender not suggesting search terms

    - by Phil
    My codebehind method: <System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()> _ Public Shared Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer, ByVal contextKey As String) As String() ' Create array of movies Dim movies() As String = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"} ' Return matching movies Return From m In movies Where (m.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase)) Select m _ .Take(count).ToArray() End Function End Class Then in my aspx page I have: <form id="form1" runat="server"> <div> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager> <br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" DelimiterCharacters="" Enabled="True" ServiceMethod="GetCompletionList" ServicePath="" TargetControlID="TextBox1" UseContextKey="True" MinimumPrefixLength="2"> </asp:AutoCompleteExtender> </div> </form> When I run the page there are no errors, but there also are no auto complete suggestions. Please help!

    Read the article

  • Converting UnicodeString to PAnsiChar in Delphi XE

    - by moodforaday
    In Delphi XE I am using the BASS audio library, which contains this function: function BASS_StreamCreateURL(url: PAnsiChar; offset: DWORD; flags: DWORD; proc: DOWNLOADPROC; user: Pointer):HSTREAM; stdcall; external bassdll; The 'url' parameter is of type PAnsiChar, so in my code I do a cast: FStreamHandle := BASS_StreamCreateURL(PAnsiChar( url ) [...] The compiler emits a warning on this line: "suspicious typecast of string to PAnsiChar". In trying to eliminate the warning, I found that the recommended way is to use a double cast: FStreamHandle := BASS_StreamCreateURL(PAnsiChar( AnsiString( url )) [...] This does eliminate the warning, but the BASS function now returns error code 2 ("cannot open file"), which tells me the URL string it receives is somehow broken. I cannot see what the bass DLL actually receives, but using a breakpoint in the debugger the string looks good: var s : PAnsiChar; begin s := PAnsiChar( AnsiString( url )); At this point string s appears fine, but the BASS function fails when I pass it. My initial code: PAnsiChar( url ) works well with BASS, but emits a warning. So what's the correct way of getting from UnicodeString to PAnsiChar without a warning?

    Read the article

  • Calling PHP functions within HEREDOC strings

    - by Doug Kavendek
    In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces. In PHP 5, it is possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example: $fn = 'testfunction'; function testfunction() { return 'ok'; } $string = <<< heredoc plain text and now a function: {$fn()} heredoc; As you can see, this is a bit more messy than just: $string = <<< heredoc plain text and now a function: {testfunction()} heredoc; There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like: ?> <!-- directly outputting html and only breaking into php for the function --> plain text and now a function: <?PHP print testfunction(); ?> The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want. So, the essence of my question is: is there a more elegant way to approach this? Edit based on responses: It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.

    Read the article

  • .NET Hashtable - "Same" key, different hashes

    - by Simon Lindgren
    Is it possible for two .net strings to have different hashes? I have a Hashtable with amongst others the key "path". When I loop through the elements in the table to print it, i can see that the key exists. When trying to looking it up however, there is no matching element. Debugging suggests that the string I'm looking for has a different hash than the one I'm supplying as the key. This code is in a Castle Monorail project, using brail as a view engine. The key I'm looking for is inserted by a brail line like this: UrlHelper.Link(node.CurrentPage.LinkText, {@params: {@path: "/Page1"}}) Then, in this method (in a custom IRoutingRule): public string CreateUrl(System.Collections.IDictionary parameters) { PrintDictionaryToLog(parameters); string url; if (parameters.Contains("path")) { url = (string)parameters["path"]; } else { return null; } } The key is printed to the log, but the function returns null. I didn't know this could even be a problem with .net strings, but I guess this is some kind of encoding issue? Oh, and this is running mono.

    Read the article

  • keep HTMLformat after replace some text (using PHP and JS)

    - by Sadi
    I would like modify HTML like I am <b>Sadi, novice</b> programmer. to I am <b>Sadi, learner</b> programmer. To do it I will search using a string "novice programmer". How can I do it please? Any idea? Thank you Sadi More clarification: I get some nice reply with possible solution. But please keep posting if you have any idea in mind. I would like to more clarify the problem just in case anyone missed it. Main post shows the problem as an example scenario. 1) Now the problem is find and replace some string without considering the tags. The tags may shows up within a single word. String may contain multiple word. Tag only appear in the content string or the document. The search phrase never contain any tags. We can easily remove all tags and do some text operation. But here the another problem shows up. 2) The tags must be preserve, even after replacing the text. That is what the example shows. Thank you Again for helping

    Read the article

  • How do I get 3 lines of text from a paragraph in C#

    - by Keltex
    I'm trying to create an "snippet" from a paragraph. I have a long paragraph of text with a word hilighted in the middle. I want to get the line containing the word before that line and the line after that line. I have the following piece of information: The text (in a string) The lines are deliminated by a NEWLINE character \n I have the index into the string of the text I want to hilight A couple other criteria: If my word falls on first line of the paragraph, it should show the 1st 3 lines If my word falls on the last line of the paragraph, it should show the last 3 lines Should show the entire paragraph in the degenative cases (the paragraph only has 1 or 2 lines) Here's an example: This is the 1st line of CAT text in the paragraph This is the 2nd line of BIRD text in the paragraph This is the 3rd line of MOUSE text in the paragraph This is the 4th line of DOG text in the paragraph This is the 5th line of RABBIT text in the paragraph Example, if my index points to BIRD, it should show lines 1, 2, & 3 as one complete string like this: This is the 1st line of CAT text in the paragraph This is the 2nd line of BIRD text in the paragraph This is the 3rd line of MOUSE text in the paragraph If my index points to DOG, it should show lines 3, 4, & 5 as one complete string like this: This is the 3rd line of MOUSE text in the paragraph This is the 4th line of DOG text in the paragraph This is the 5th line of RABBIT text in the paragraph etc. Anybody want to help tackle this?

    Read the article

  • Ignore case in Python strings

    - by Paul Oyster
    What is the easiest way to compare strings in Python, ignoring case? Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads). I guess I'm looking for an equivalent to C's stricmp(). [Some more context requested, so I'll demonstrate with a trivial example:] Suppose you want to sort a looong list of strings. You simply do theList.sort(). This is O(n * log(n)) string comparisons and no memory management (since all strings and list elements are some sort of smart pointers). You are happy. Now, you want to do the same, but ignore the case (let's simplify and say all strings are ascii, so locale issues can be ignored). You can do theList.sort(key=lambda s: s.lower()), but then you cause two new allocations per comparison, plus burden the garbage-collector with the duplicated (lowered) strings. Each such memory-management noise is orders-of-magnitude slower than simple string comparison. Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp) and it is as fast and as memory-friendly as theList.sort(). You are happy again. The problem is any Python-based case-insensitive comparison involves implicit string duplications, so I was expecting to find a C-based comparisons (maybe in module string). Could not find anything like that, hence the question here. (Hope this clarifies the question).

    Read the article

< Previous Page | 107 108 109 110 111 112 113 114 115 116 117 118  | Next Page >